What is the idiomatic Python equivalent of this C/C++ code?
void foo()
{
static int counter = 0;
counter++;
Using an attribute of a function as static variable has some potential drawbacks:
Idiomatic python for the second issue would probably be naming the variable with a leading underscore to signal that it is not meant to be accessed, while keeping it accessible after the fact.
An alternative would be a pattern using lexical closures, which are supported with the nonlocal
keyword in python 3.
def make_counter():
i = 0
def counter():
nonlocal i
i = i + 1
return i
return counter
counter = make_counter()
Sadly I know no way to encapsulate this solution into a decorator.