MathCurvesSurfacesWallpaper GroupsGallerySoftwarePOV-Ray
ProgramingLinuxPerl PythonHTMLCSSJavaScriptPHPJavaLang DesignEmacsUnicode ♥

Python: Function with State (closure)

,

Is it possible in Python to create a function that maintains a variable value? Something like this (which doesn't work):

# -*- coding: utf-8 -*-
# python

globe = 0
def myFun():
 globe = globe + 1
 return globe

See answers below:


The simplest is to precede the setting of global variables by “global” keyword.

# -*- coding: utf-8 -*-
# python

globe = 0
def myFun():
    global globe
    globe += 1
    return globe

myFun()
myFun()
myFun()
print globe

The “global” keyword tells Python that the variable you are using is in the global context. Source doc.python.org

Another way is to use a list instead of a variable.

# -*- coding: utf-8 -*-
# python

globe= [ 0 ]
def myFun():
    globe[0] = globe[0] + 1
    return globe[0]

myFun()
myFun()
myFun()
print globe[0]

The most clean way is using the OOP.

# -*- coding: utf-8 -*-
# python

def myFun():
    myFun.x += 1
    return myFun.x
myFun.x = 0

myFun()
myFun()
myFun()
print myFun.x

Thanks to many people on comp.lang.python forum. {Patrick Useldinger, Andrew Clover, Andrew Koenig, …} Source groups.google.com.

blog comments powered by Disqus