[Tutor] C-like local static var in Py ?

Yann Le Du yann.ledu@noos.fr
Sun Dec 1 18:09:02 2002


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On Sun, 1 Dec 2002, Aztech Guy wrote:

> (Checked docs, couldn't find relevant info)
> 
> How can I get the effect of a "local static" variable as in C - in Python ?
> e.g. with this C function  ...
> void f(void)
> 
> {
>     static int call_count = 0;
>     call_count++;
>     printf("call_count = %d\n", call_count);
>     /* other code */
> }
> 
> ... each time I call f(), the value of call_count is incremented by 1
> over the previous value it had when the function was last exited, unlike
> an "automatic" local variable (which it would be if I omitted the
> "static" keyword - and which would get reset to 0 on each call to f() ).
> I know this can be done by using OO, i.e. a class, and retaining state
> with a member variable, but I want to see if it can be done in non-OO,
> procedural code.

I suggest this :

def inc(v=[0]):
        v[0]+=1
        print v[0]

First time you call inc(), it will print 1, then 2, etc...

You can reset this by setting v=[0] outside of that function.

Y
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (GNU/Linux)
Comment: For info see http://quantumlab.net/pine_privacy_guard/

iD8DBQE96pY/t4mG++uo5yQRAjygAJ4pfMaPeVM4kStZ2KK8GniHNtyoQACgsRyO
a4lQdJJOCPHJVQklnTQ0nrM=
=9Ow+
-----END PGP SIGNATURE-----