Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Python equivalent of static variables inside a function?

Tags:

python

static

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?

like image 508
andrewdotnich Avatar asked Nov 10 '08 23:11

andrewdotnich


People also ask

Are there static variables in Python?

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.

What are static variables inside a function?

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.

What can I use instead of a static variable?

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.

What are static attributes in Python?

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.


2 Answers

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)

like image 183
Claudiu Avatar answered Sep 21 '22 04:09

Claudiu


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.

like image 28
vincent Avatar answered Sep 25 '22 04:09

vincent