Pythonic way to do static local variables?
George Sakkis
gsakkis at rutgers.edu
Mon Apr 25 22:19:37 EDT 2005
> I've a function that needs to maintain an ordered sequence between
> calls.
>
> In C or C++, I'd declare the pointer (or collection object) static at
> the function scope.
>
> What's the Pythonic way to do this?
>
> Is there a better solution than putting the sequence at module scope?
Yes, there is; it's called "object oriented programming". In general,
whenever you find that one or more functions have to access a context
that is not passed in explicitly as arguments, the proper (pythonic and
non-pythonic) way is to define them as a method in a class that stores
this context.
class Foo(object):
def __init__(self):
self._context = # something
def method(self):
x = self._context
# do stuff
self._context.update()
Another solution is function/method attributes. This is handy if OO
seems an overkill for a single function, or in case of methods, if you
don't want to pollute the instance namespace with something used by a
single method:
def foo():
# foo.x is like a C static
try: foo.x +=1
except AttributeError:
foo.x = 1
return foo.x
for i in xrange(10): print foo()
if foo() is a method, it becomes a little more cumbersome, first
because you have to refer to the class name and (less obviously)
because user defined attributes are not allowed in instance methods (I
wonder why); you have to refer to the wrapped function:
class Foo(object):
def foo(self):
try: Foo.foo.im_func.x += 1
except AttributeError:
Foo.foo.im_func.x = 1
return Foo.foo.x
foo = Foo().foo
for i in xrange(10): print foo()
Hope this helps,
George
More information about the Python-list
mailing list