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?
Yes, definitely possible to write static variables and methods in python. Static Variables : Variable declared at class level are called static variable which can be accessed directly using class name.
A static variable is a variable that is declared using the keyword static. The space for the static variable is allocated only one time and this is used for the entirety of the program. Once this variable is declared, it exists till the program executes.
It's always better than global objects whose initialization depend on other global objects. The other alternative is Singleton Pattern. Both can solve similar problem.
Static means, that the member is on a class level rather on the instance level. Static variables exist only on class level and aren't instantiated. If you change a static variable in one instance of the class, the change will affect its value in all other instances.
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)
You can add attributes to a function, and use it as a static variable.
def myfunc(): myfunc.counter += 1 print myfunc.counter # attribute must be initialized myfunc.counter = 0
Alternatively, if you don't want to setup the variable outside the function, you can use hasattr()
to avoid an AttributeError
exception:
def myfunc(): if not hasattr(myfunc, "counter"): myfunc.counter = 0 # it doesn't exist yet, so initialize it myfunc.counter += 1
Anyway static variables are rather rare, and you should find a better place for this variable, most likely inside a class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With