You can make static variables inside a function in many ways in Python. If declaring a static variable in a function means variable throughout the lifetime of the program.
Python static variable in a function examples
Simple 3 example code for it:-
Add attributes to a function
You can add attributes to a function, and use it as a static variable. Count how many times functions have been called using a static variable.
def foo(): foo.counter += 1 print("Counter is %d" % foo.counter) foo.counter = 0 foo() foo()
Initialization code at the top using decorator
If you want the counter initialization code at the top instead of the bottom, you can create a decorator:
def static_vars(**kwargs): def decorate(func): for k in kwargs: setattr(func, k, kwargs[k]) return func return decorate # Then use the code like this: @static_vars(counter=0) def foo(): foo.counter += 1 print("Counter is %d" % foo.counter) foo()
Output: Counter is 1
Alternatively, if you don’t want to set up the variable outside the function, you can use hasattr() to avoid an AttributeError exception:
def myfunc(): if not hasattr(myfunc, "counter"): myfunc.counter = 0 # it doesn't exist yet, so initialize it myfunc.counter += 1 return myfunc.counter print(myfunc()) print(myfunc())
Do comment if you have any doubts or suggestions on this Python variable topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.