Static Variables in Python.
I use this pattern frequently across different projects and would like to keep it here for reference.
Python doesn’t have C-style static variables natively. (Although it supports class variables, which can be used for a similar purpose in OOP.) However, since functions are also objects in Python, it’s possible to embed variables inside the function. An elegant solution on Stack Overflow creates a decorator for static variables.
def static_vars(**kwargs):
def decorate(func):
for k in kwargs:
setattr(func, k, kwargs[k])
return func
return decorate
@static_vars(counter=0)
def foo():
foo.counter += 1
print(f"Counter is {foo.counter}")