Equiv of C's static local vars in Py ?

Anton Vredegoor anton at vredegoor.doge.nl
Mon Dec 2 07:50:54 EST 2002


On 1 Dec 2002 12:10:22 -0800, aztech1200 at yahoo.com (Az Tech) wrote:

>What, if any, is the equivalent of C's static local 
>variables in Python ? E.g. if I have a C function :
>
>void f(void)
>{
>  static int call_count = 0;
>  call_count++;
>  printf("f() has been called %d times\n", call_count);
>  /* 
>    other code
>  */
>}
>
>This function f retains the value of call_count between successive 
>calls to it - so each time it is called, the value for call_count
>printed out will be one more than the last one.
>
>Can this be done in Python and if so, how ?

See code below,
		Anton

from __future__ import generators

def counter():
    call_count = 0
    while 1:
       call_count+=1
       yield call_count

def test():
    f = counter()
    for i in range(10):
        print "f has been called %d times" %f.next()
        #other code

if __name__=='__main__':
    test()




More information about the Python-list mailing list