A bit reversed, but this should work:

def foo():
    foo.counter += 1
    print "Counter is %d" % foo.counter
foo.counter = 0

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

It'll still require you to use the foo. prefix, unfortunately.

(Credit: @ony)

Answer from Claudiu on Stack Overflow
🌐
Scientech Easy
scientecheasy.com › home › blog › static variable in python
Static Variable in Python - Scientech Easy
August 1, 2026 - Let’s consider a scenario where we will count how many times a function is called. We can achieve this using a static variable, as explained in the below example code. ... # Python program to count the function call. class Counter: count = 0 # class variable declaration.
🌐
Medium
medium.com › xster-tech › pythons-function-static-variable-5232a8e44429
Python’s Function Static Variable | by xster | xster | Medium
March 22, 2017 - So you want a variable that stays between different calls of a function. Not the sexiest thing ever but always handy in small programs. There’s tons of ways of doing this. You can embark on a quest to find the meaning of Pythonic or take this method that’s relatively simple: def a(): if not hasattr(a, "b"): a.b = 0 a.b += 1 print a.b ... Note attribute ‘b’ of ‘a’ does not exist until you declare it for a first time. My main preference here is that ‘static’ variables used this way does not spill onto the rest of your code.
🌐
EyeHunts
tutorial.eyehunts.com › home › python static variable in a function | example code
Python static variable in a function | Example code
August 8, 2022 - 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() ... If you want the counter initialization code at the top instead of the bottom, you can create a decorator:
🌐
Python Guides
pythonguides.com › use-static-variables-in-python-functions
How To Use Static Variables In Python Functions?
March 19, 2025 - Static variables in Python are variables that retain their value between function calls. Unlike regular local variables, which are re-initialized every time a function is called, static variables maintain their state.
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 33025 › static-variables-in-python
static variables in python [SOLVED] | DaniWeb
September 27, 2005 - ... Python does not have C/C++-style static locals, but in modern Python the cleanest equivalent is a closure with a nonlocal binding so the state lives alongside the function and is not global.
Top answer
1 of 7
40

Assuming what you want is "a variable that is initialised only once on first function call", there's no such thing in Python syntax. But there are ways to get a similar result:

1 - Use a global. Note that in Python, 'global' really means 'global to the module', not 'global to the process':

_number_of_times = 0

def yourfunc(x, y):
    global _number_of_times
    for i in range(x):
        for j in range(y):
            _number_of_times += 1

2 - Wrap you code in a class and use a class attribute (ie: an attribute that is shared by all instances). :

class Foo(object):
    _number_of_times = 0

    @classmethod
    def yourfunc(cls, x, y):
        for i in range(x):
            for j in range(y):
                cls._number_of_times += 1

Note that I used a classmethod since this code snippet doesn't need anything from an instance

3 - Wrap you code in a class, use an instance attribute and provide a shortcut for the method:

class Foo(object):
    def __init__(self):
         self._number_of_times = 0

    def yourfunc(self, x, y):
        for i in range(x):
            for j in range(y):
                self._number_of_times += 1

yourfunc = Foo().yourfunc

4 - Write a callable class and provide a shortcut:

class Foo(object):
    def __init__(self):
         self._number_of_times = 0

    def __call__(self, x, y):
        for i in range(x):
            for j in range(y):
                self._number_of_times += 1


yourfunc = Foo()

4 bis - use a class attribute and a metaclass

class Callable(type):
    def __call__(self, *args, **kw):
        return self._call(*args, **kw)

class yourfunc(object):
    __metaclass__ = Callable

    _numer_of_times = 0

    @classmethod
    def _call(cls, x, y):
        for i in range(x):
            for j in range(y):                 
                cls._number_of_time += 1

5 - Make a "creative" use of function's default arguments being instantiated only once on module import:

def yourfunc(x, y, _hack=[0]):
    for i in range(x):
        for j in range(y):
            _hack[0] += 1

There are still some other possible solutions / hacks, but I think you get the big picture now.

EDIT: given the op's clarifications, ie "Lets say you have a recursive function with default parameter but if someone actually tries to give one more argument to your function it could be catastrophic", it looks like what the OP really wants is something like:

# private recursive function using a default param the caller shouldn't set
def _walk(tree, callback, level=0):
    callback(tree, level)
    for child in tree.children:
        _walk(child, callback, level+1):

# public wrapper without the default param
def walk(tree, callback):
    _walk(tree, callback)

Which, BTW, prove we really had Yet Another XY Problem...

2 of 7
8

You can create a closure with nonlocal to make them editable (python 3.x only). Here's an example of a recursive function to calculate the length of a list.

def recursive_len(l):
    res = 0
    def inner(l2):
        nonlocal res
        if l2:
            res += 1
            inner(l2[1:])
    inner(l)
    return res

Or, you can assign an attribute to the function itself. Using the trick from here:

def fn(self):
    self.number_of_times += 1
fn.func_defaults = (fn,)
fn.number_of_times = 0

fn()
fn()
fn()
print (fn.number_of_times)
Find elsewhere
🌐
JanBask Training
janbasktraining.com › community › python-python › what-is-the-python-equivalent-of-static-variables-inside-a-function
What is the Python equivalent of static variables inside a function? | JanBask Training Community
April 5, 2021 - How to implement static member ... ... To get a python static variable in function you can add attributes to a function, and use it as a static variable....
🌐
Codemia
codemia.io › home › knowledge hub › what is the python equivalent of static variables inside a function?
What is the Python equivalent of static variables inside a function? | Codemia
January 9, 2025 - This mimics a static variable by keeping track of the number of times the function has been called. Another way to create static-like behavior in Python is through the use of mutable default arguments. Default argument values are evaluated only once at the point of function definition in the defining scope.
🌐
GeeksforGeeks
geeksforgeeks.org › python › g-fact-34-class-or-static-variables-in-python
Class (Static) and Instance Variables in Python - GeeksforGeeks
Class variables are shared by all objects of a class, whereas instance variables are unique to each object. Unlike languages such as Java or C++, Python does not require a static keyword.
Published: March 6, 2026
🌐
FavTutor
favtutor.com › blogs › static-variable-python
Static Variable in Python (How to Create and Access it?)
September 12, 2022 - When we want to leave something as a constant, we use the term "static." In Python, 'static' is needed when we want to create any variable or method for the class, i.e. shared by all instances (objects) of the class.
🌐
Edureka Community
edureka.co › home › community › categories › python › python equivalent for static variables within a...
Python equivalent for static variables within a function | Edureka Community
October 17, 2018 - What is the idiomatic Python equivalent of this C/C++ code? void fun() { static int ... does placing the function into a class change anything?
🌐
Medium
medium.com › @ryan_forrester_ › python-static-variables-complete-guide-f14bed644a6d
Python Static Variables: Complete Guide | by ryan | Medium
October 24, 2024 - They belong to the class itself, not individual objects: class Student: # This is a static variable school_name = "Python High" def __init__(self, name): # This is an instance variable self.name = name # Accessing the static variable through the class print(Student.school_name) # Output: Python High # Creating instances student1 = Student("Alice") student2 = Student("Bob") # Accessing through instances print(student1.school_name) # Output: Python High print(student2.school_name) # Output: Python High
Top answer
1 of 3
2
  • I really don't think Value is a help here.
    Whilst I can see the allure of only assigning x to static.x. This just looks like a smart, but not exactly good, work around to get default values.

    You can just have with_statics take keyword arguments as the defaults.

    def with_statics(**defaults):
        statics = Statics(defaults)  # Implementation left to imagination
        def inner(f):
            @wraps(f)
            def wrapper(*args, **kwargs):
                return f(statics, *args, **kwargs)
            return wrapper
        return inner
    
  • Defining Value inside of two other classes is not great. You can just move it to the global scope and change the isinstance check to not need to use indexing.

    If you still want the class on the other classes then you can just assign it as a class attribute.

    class Current:
        Value = Value
    
        ...
    
  • I think I'm fairly well versed in the magical Python arts. However your code is just confusing.

  • Your code looks like it's a hack when a hack isn't needed.

    To highlight this I will convert your doctests to not use your code.

def counter():
    counter.val += 1
    return counter.val


counter.val = 0
print(counter(), counter(), counter())


def get_string():
    print("Getting string")
    return ""


def record(text):
    if record.recorded is None:
        record.recorded = get_string()
    record.recorded += text
    return record.recorded


record.recorded = None
print(record("Hello"))
print(record(", world!"))

Yes it works. However, honestly, why would you want this?

2 of 3
1

In the few cases I've wanted C-style static variables, I've used a Class with a __call__() method:

class Foo:
    a = 1
    b = 2

    def __call__(self):
        print(self.a, self.b)
foo = Foo()

foo()

Or, you could use a function decorator

def staticvars(**vars):
    def f(func):
        for k,v in vars.items():
            setattr(func, k, v)
        return func
    return f

@staticvars(a=1,b=2)
def foo():
    print(foo.a, foo.b)

Or, under the idea "it's easier to get forgiveness than permission":

def counter():
    try:
        counter.x += 1

    except AttributeError:
        counter.x = 1

    return counter.x


print(counter(), counter(), counter())   # prints: 1, 2, 3
🌐
Javatpoint
javatpoint.com › static-in-python
Static in Python - Javatpoint
How to Create Global Variables in Python Functions
🌐
Wiingy
wiingy.com › home › learn › python › class or static variable in python
Class or Static Variable in Python
January 30, 2025 - In this example, ‘count’ is a static variable of the Student class, and it is shared by all instances of the class. The value of ‘count’ is incremented each time a new instance of the class is created. In Python, you must use the’static’ keyword before the variable name to define a static variable.
🌐
HCL GUVI
studytonight.com › python › python-static-keyword
HCL GUVI | Learn to code in your native language
HCL GUVI's Data Science Program was just fantastic. It covered statistics, machine learning, data visualization, and Python within its curriculum.