static variables in Python?

bearophileHUGS at bearophileHUGS at
Wed Jul 30 01:07:35 CEST 2008

> OK, I guess that in Python the only way to do what I want to do
> is with objects...

There are other ways, like assigning the value out of the function,
because Python functions too are objects:

def iamslow():
    return 100
def foo(x):
    return x + foo.y
foo.y = iamslow() # slow computation
print foo(1)
print foo(2)

Output is:

Another way is this, a bit more clean, with the same output:

def iamslow():
    return 100
def foo(x, y=iamslow()):
    return x + y
print foo(1)
print foo(2)

But I suggest you to use a class in this situation, it's often the way
that will keep your code more bug-free, and more readable by near-
casual readers too. Python philosophy asks you to write readable code
instead of clever code when possible, this is a difference from Perl,
I presume.


More information about the Python-list mailing list