A frequently asked question is whether there is an equivalent of static variables inside functions in Python. There are many answers, such as creating wrapper classes, using nested functions, decorators, etc.
One of the most elegant solutions I found was this , which I slightly modified:
def foo(): # see if foo.counter already exists try: test = foo.counter # if not, initialize it to whatever except AttributeError: foo.counter = 0 # do stuff with foo.counter ..... .....
Example:
static.py
def foo(x): # see if foo.counter already exists try: test = foo.counter # if not, initialize it to whatever except AttributeError: foo.counter = 0 foo.counter += x print(foo.counter) for i in range(10): foo(i)
Exit
$ python static.py 0 1 3 6 10 15 21 28 36 45
Is there a reason I should avoid this method? How does it work?
python static
abalter
source share