static variables?

Bengt Richter bokr at oz.net
Tue Nov 19 15:02:47 EST 2002


On Tue, 19 Nov 2002 04:18:16 GMT, "Josh" <jslmaslk at earthlink.net> wrote:

>Hi guys,
>
>I am a python newbie, and I am sure there is an easy answer but, Is there
>any equivalent to C's static variables in Python? If not, how can you have
>variables inside a function, that 'remember' their values between function
>calls?
>
There's more than one way to get the effect.
You can do it with a function or you can do it
with a class instance that acts like a function.

you would like the effect, say, of

def foo():
    # <magic one-time initialization of static x value>
    print x
    x = x + 1

We need to attach the value to something persistent. The function itself
is handy. You can just attach named values as attributes, and they'll be
"remembered":

 >>> def foo():
 ...     global foo
 ...     print foo.x
 ...     foo.x += 1
 ...
 >>> foo.x = 3
 >>> foo()
 3
 >>> foo()
 4
 >>> foo()
 5

But this depends on foo finding its own name in the global directory
You can avoid that by defining it inside another function that returns
it. It finds itself in the enclosing name space of the outer function,
and that environment is preserved in a closure attached to the returned
function, so it's not lost when the outer function returns:


 >>> def mkfoo():
 ...    def foo():
 ...       print foo.x
 ...       foo.x += 1
 ...    foo.x = 0
 ...    return foo
 ...
 >>> foo = mkfoo()
 >>> foo()
 0
 >>> foo.x
 1

You could pass something to mkfoo to initialize foo.x with
if you wanted to.

Also, you could use other ways to store the value. An attribute
is just easy to write.

To make a class instance that acts similarly, but uses self.x instead of foo.x,
you can do this:

 >>> class Foo:
 ...     def __init__(self, x=0): self.x = x
 ...     def __call__(self):
 ...         print self.x
 ...         self.x += 1
 ...
 >>> foo = Foo(3)
 >>> foo()
 3
 >>> foo()
 4
 >>> foo()
 5

mkfoo() and Foo() create independent foo's that have separate states,
but you could make them all operate on a single shared state also.

Regards,
Bengt Richter



More information about the Python-list mailing list