Licheng Fang wrote:

> On Apr 14 2003, 10:30 pm, Alex Martelli <[EMAIL PROTECTED]> wrote:
>> Sebastian Wilhelmi wrote:
>> > 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 ;-)
>>
>> Specifically: a nested function cannot *RE-BIND* a variable of
>> an outer function.
>>
> 
> Sorry to dig up this old thread, but I would like to know what's the
> rationale is. Why can't a nested function rebind a variable of an
> outer function?

Because the lack of variable declarations in python makes the
left-hand-side-appearance of a variable the exact distinction criteria
between inner and outer scopes. Thus it can't rebind them. What you can do
is to use mutables as container for outer variables:


def outer():
    v =[1]
    def increment():
        a = v[0]
        a += 1
        v[0] = a
    increment()
    print v[0]


Diez
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to