python static variable in function

Solutions on MaxInterview for python static variable in function by the best coders in the world

showing results for - "python static variable in function"
Delfina
01 Jun 2019
1#You can make static variables inside a function in many ways.
2#____________________________________________________________#
3"""1/You can add attributes to a function, and use it as a
4static variable."""
5def foo():
6    foo.counter += 1
7    print ("Counter is %d" % foo.counter)
8foo.counter = 0 
9
10#____________________________________________________________#
11"""2/If you want the counter initialization code at the top
12instead of the bottom, you can create a decorator:"""
13def static_vars(**kwargs):
14    def decorate(func):
15        for k in kwargs:
16            setattr(func, k, kwargs[k])
17        return func
18    return decorate
19  
20#Then use the code like this:
21@static_vars(counter=0)
22def foo():
23    foo.counter += 1
24    print ("Counter is %d" % foo.counter)
25
26#____________________________________________________________#
27"""3/Alternatively, if you don't want to setup the variable
28outside the function, you can use hasattr() to avoid an
29AttributeError exception:"""
30def myfunc():
31    if not hasattr(myfunc, "counter"):
32        myfunc.counter = 0  # it doesn't exist yet, so initialize it
33    myfunc.counter += 1
34  
35#____________________________________________________________#