Thursday, July 9, 2009

Pythonic way to do static local variables

If you are using C++ or Java, you man have used static local variables to define variables that would retain its value between function calls.

In python there is no obvious way to do it, and you need to exploit some hidden python characteristics, namely function/method attributes.

If you need that trick with a function (not bound to an instance) it is rather straight forward:

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 an instance method the straight froward way would have been to use an instance variable of the container class to hold the value for you, but that would pollute the instance namespace with variables of special needs and never used outside the method scope.

You can still do something similar to the trick above but it becomes a little more cumbersome.

Firstly because you have to refer to the class name, e.g. Bar.foo.*

Secondly and (less obviously) because user defined attributes are not allowed in instance methods!

I don't like as much as you do but it is a fact of life, read more here;

thus you'd have to refer to the wrapped function referenced by the method instance attribute im_func:

class Bar(object):
def foo(self):
try: Bar.foo.im_func.x += 1
except AttributeError:
Bar.foo.im_func.x = 1
return Bar.foo.x
foo = Bar().foo
for i in xrange(10): print foo()

You may argue that it is not an intuitive syntax, may be you are right, I only did it for the kicks :)


1 comment:

  1. 192.168.0.1 Many Netgear and D-Link model routers use 192.168.0.1 as their default IP address. It is used in a private IPv4 network address as the router

    ReplyDelete