Equiv of C's static local vars in Py ?

Terry Reedy tjreedy at udel.edu
Sun Dec 1 18:02:17 EST 2002


> What, if any, is the equivalent of C's static local
> variables in Python ? E.g. if I have a C function :

> P.S. I know this can be done using OO in Py (by declaring a class
that
> contains a member/field and then instantiating objects of that
class);
> but I have an app that I want to first develop in a non-OO
> (procedural) style, and only then convert it to OO style
> (for the purpose of learning/exploring language Python features).

Option 1 (tested):

def f(cnt=[0]):
    cnt[0] = cnt[0]+1
    print 'f called', cnt[0], 'times'

f()
f()
f()
f([1.1])
f()

# outputs

f called 1 times
f called 2 times
f called 3 times
f called 2.1 times
f called 4 times

#f(nonsubscriptable) gives typeerror

Option 2 (also tested)

def make_f():
    cnt=[0]
    def _():
        cnt[0] = cnt[0]+1
        print 'f called', cnt[0], 'times'
    return _

f = make_f()
f()
f()
f()

# again gives

f called 1 times
f called 2 times
f called 3 times

#f(anything) is typeerror

Terry J. Reedy





More information about the Python-list mailing list