Python Programming
Static Variables
Function Coding
Programming Languages
Coding Techniques

Python static variable in a function: the equivalents

Codemia Knowledge Hub ·

Python has no static local variables like C or C++, but you can keep state between calls in four ways: store it as an attribute on the function, capture it in a closure with nonlocal, wrap it in a class, or rely on a mutable default argument. Each avoids a global variable.

Function attributes

Functions are first-class objects in Python, so you can attach attributes to them. This is the most direct imitation of a static variable:

python
1def counter():
2    if hasattr(counter, 'count'):
3        counter.count += 1
4    else:
5        counter.count = 1
6    return counter.count

counter.count keeps its value between calls, so it counts how many times counter() has run.

Mutable default arguments

Default argument values are evaluated once, when the function is defined. If the default is mutable and you modify it, the change persists across calls:

python
def append_to(element, my_list=[]):
    my_list.append(element)
    return my_list

This often causes bugs when a function was not meant to share state between calls, so use it deliberately or not at all.

Closures with nonlocal

A nested function can reference variables from its enclosing scope, and nonlocal lets it modify them:

python
1def make_counter():
2    count = 0
3    def counter():
4        nonlocal count
5        count += 1
6        return count
7    return counter
8
9my_counter = make_counter()

Each call to my_counter() increments and returns count, which stays hidden from the global scope.

A class

A class is more verbose but gives the most control, especially when several related values need to persist:

python
1class Counter:
2    def __init__(self):
3        self.count = 0
4
5    def increment(self):
6        self.count += 1
7        return self.count

Choosing a technique

TechniqueUse CaseProsCons
Function AttributesSimple function-level static variablesStraightforwardNot thread-safe
Mutable Default ArgumentsSimple use cases, default cachingEasy to use; less codeCan lead to unexpected bugs
Closures and NonlocalComplex stateful functions, encapsulationGood encapsulation; clear and cleanSlightly more complex
Class-BasedComplex state, multiple related static variablesFull control, encapsulationMore verbose; might be overkill for simplicity

The right choice depends on whether you value simplicity, encapsulation or flexibility more for the code at hand.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms