patternpythonCriticalCanonical
What is the Python equivalent of static variables inside a function?
Viewed 0 times
variablesinsidefunctiontheequivalentstaticwhatpython
Problem
What is the idiomatic Python equivalent of this C/C++ code?
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?
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?
Solution
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
(Credit: @ony)
def foo():
foo.counter += 1
print "Counter is %d" % foo.counter
foo.counter = 0If 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 decorateThen use the code like this:
@static_vars(counter=0)
def foo():
foo.counter += 1
print "Counter is %d" % foo.counterIt'll still require you to use the
foo. prefix, unfortunately.(Credit: @ony)
Code Snippets
def foo():
foo.counter += 1
print "Counter is %d" % foo.counter
foo.counter = 0def static_vars(**kwargs):
def decorate(func):
for k in kwargs:
setattr(func, k, kwargs[k])
return func
return decorate@static_vars(counter=0)
def foo():
foo.counter += 1
print "Counter is %d" % foo.counterContext
Stack Overflow Q#279561, score: 892
Revisions (0)
No revisions yet.