Question about nested scopes

Emile van Sebille emile at fenx.com
Wed Oct 8 10:45:12 EDT 2003


"Miki Tebeka" <tebeka at cs.bgu.ac.il> wrote in message
news:33803989.0310080613.68b8b25f at posting.google.com...
> Hello,
>
> Can anyone explain why:
> >>> def make_inc(n):
> s = n
> def inc(i):
> s += i
> return s
> return inc
[error snipped]
>
> But:
> >>> def make_inc(n):
> s = [n]
> def inc(i):
> s[0] += i
> return s[0]
> return inc

For the same reason as
>>> s=1
>>> s is 1
True
>>> s+=1
>>> s is 2
True

Assignment to from within a function creates a local variable.  Modification
of a mutable does not.

--
Emile van Sebille
emile at fenx.com






More information about the Python-list mailing list