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?
You can add attributes to a function, and use it as a static variable.
Alternatively, if you don't want to setup the variable outside the function, you can use
hasattr()
to avoid anAttributeError
exception:Anyway static variables are rather rare, and you should find a better place for this variable, most likely inside a class.
Building on Daniel's answer (additions):
The reason why I wanted to add this part is , static variables are used not only for incrementing by some value, but also check if the static var is equal to some value, as a real life example.
The static variable is still protected and used only within the scope of the function use_foo()
In this example, call to foo() functions exactly as(with respect to the corresponding c++ equivalent) :
if class Foo is defined restrictively as a singleton class, that would be ideal. This would make it more pythonic.
Prompted by this question, may I present another alternative which might be a bit nicer to use and will look the same for both methods and functions:
If you like the usage, here's the implementation:
All of previous solutions attach a counter attribute to the function, usually with convoluted logic to handle the initialization. This is inappropriate for new code.
In Python 3, the right way is to use a
nonlocal
statement:See PEP 3104 for the specification of the
nonlocal
statement.After trying several approaches I end up using an improved version of @warvariuc's answer:
This answer builds on @claudiu 's answer.
I found that my code was getting less clear when I always had to prepend the function name, whenever I intend to access a static variable.
Namely, in my function code I would prefer to write:
instead of
So, my solution is to :
statics
attribute to the functionstatics
as an alias tomy_function.statics
Remark
My method uses a class named
Bunch
, which is a dictionary that supports attribute-style access, a la JavaScript (see the original article about it, around 2000)It can be installed via
pip install bunch
It can also be hand-written like so: