Skip to content

Python static variable in a function | Example code

  • by

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()

Output:

Python static variable in a function

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

Use hasattr()

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())

Output:

1
2

Do comment if you have any doubts or suggestions on this Python variable topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading