Static Variables in Python

Posted on Prş 25 Ekim 2018 in new • 1 min read

I'm using this too much in different projects and would like to keep it here.

Python doesn't have C style static variables natively. (Although it supports class variables which can be used for similar purpose in OOP.) However, as the functions are also objects in Python, it's possible to embed variables inside the function. An elegant solution at SO 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 "Counter is %d" % foo.counter