In C a static variable inside a function is only visible inside that function’s scope, but its lifetime is the entire life of the program, and it’s only initialized once.
There is NO equivalence in Python.
So if you want to be a proper python programmer you should just accept that! Use a class, use a global variable, etc.
However there are workarounds if you’ve got a really good reason to want to use variables in a static way:
def my_function():
my_function.my_static_variable+= 1
print ("Value is " + str(my_function.my_static_variable))
#static variables initialisation
my_function.my_static_variable= 3
Creating static variables at the top of a function
A useful way of being able to initialize your static variables at the top of a function (much clear to read and understand for long functions)
#**********************************************
#***** STATIC VARIABLE DECORATOR FUNCTION *****
#**********************************************
def create_static_variable(**kwargs):
def decorate(func):
for k in kwargs:
setattr(func, k, kwargs[k])
return func
return decorate
#You can now do this for static variables inside a function:
#@create_static_variable(my_static_variable = 0) #<<<The @ symbol is a decorator and passes the function following it to the call
# #<<<Notice the function name is not included here (but must be when it is used in the function)
#def my_function():
# my_function.my_static_variable += 1
# print ("Value now is " + str(my_function.my_static_variable))
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.