accessing a functions var from a subfunction.

Sebastian Wilhelmi seppi at seppi.de
Mon Apr 14 10:16:52 EDT 2003


Hi,

I would like to do the following:

-------8<-------8<-------8<-------8<-------
def test ():
    count = 0
    def inc_count ():
        count += 1
    inc_count ()
    inc_count ()
    print count

test ()
-------8<-------8<-------8<-------8<-------

This doesn't work (and I even understand, why ;-)

One solution is the following, which I however do not see as very
clean or nice.

-------8<-------8<-------8<-------8<-------
def test ():
    count = [0]
    def inc_count ():
        count[0] += 1
    inc_count ()
    inc_count ()
    print count[0]

test ()
-------8<-------8<-------8<-------8<-------

Now my question: Is there some way to achieve this with a nicer
syntax?
Using 'global' would not count, as that would make a variable
unnecessarily known to the outside.

Thanks,
Sebastian




More information about the Python-list mailing list