An oft-asked question is whether there is an equivalent to 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 have 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)
output
$ python static.py
0
1
3
6
10
15
21
28
36
45
Is there any reason I should avoid this method? How the heck does it work, anyway?