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?
Much like vincent's code above, this would be used as a function decorator and static variables must be accessed with the function name as a prefix. The advantage of this code (although admittedly anyone might be smart enough to figure it out) is that you can have multiple static variables and initialise them in a more conventional manner.
Another (not recommended!) twist on the callable object like https://stackoverflow.com/a/279598/916373, if you don't mind using a funky call signature, would be to do
A bit reversed, but this should work:
If you want the counter initialization code at the top instead of the bottom, you can create a decorator:
Then use the code like this:
It'll still require you to use the
foo.
prefix, unfortunately.EDIT (thanks to ony): This looks even nicer:
Other answers have demonstrated the way you should do this. Here's a way you shouldn't:
Default values are initialized only when the function is first evaluated, not each time it is executed, so you can use a list or any other mutable object to store static values.
Python customarily uses underscores to indicate private variables. The only reason in C to declare the static variable inside the function is to hide it outside the function, which is not really idiomatic Python.
I personally prefer the following to decorators. To each their own.