What is the idiomatic Python equivalent of this C/C++ code?
void foo()
{
static int counter = 0;
counter++;
printf("counter is %d\n", counter);
}
specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?
Python doesn't have static variables but you can fake it by defining a callable class object and then using it as a function. Also see this answer.
Note that
__call__
makes an instance of a class (object) callable by its own name. That's why callingfoo()
above calls the class'__call__
method. From the documentation:Here is a fully encapsulated version that doesn't require an external initialization call:
In Python, functions are objects and we can simply add, or monkey patch, member variables to them via the special attribute
__dict__
. The built-invars()
returns the special attribute__dict__
.EDIT: Note, unlike the alternative
try:except AttributeError
answer, with this approach the variable will always be ready for the code logic following initialization. I think thetry:except AttributeError
alternative to the following will be less DRY and/or have awkward flow:EDIT2: I only recommend the above approach when the function will be called from multiple locations. If instead the function is only called in one place, it's better to use
nonlocal
:A static variable inside a Python method
Soulution n +=1
A little bit more readable, but more verbose:
A global declaration provides this functionality. In the example below (python 3.5 or greater to use the "f"), the counter variable is defined outside of the function. Defining it as global in the function signifies that the "global" version outside of the function should be made available to the function. So each time the function runs, it modifies the value outside the function, preserving it beyond the function.