behavior difference for mutable and immutable variable in function definition

James Stroud jstroud at mbi.ucla.edu
Fri May 4 18:07:01 EDT 2007


jianbing.chen at gmail.com wrote:
> Hi,
> 
> Can anyone explain the following:
> 
> Python 2.5 (r25:51908, Apr  9 2007, 11:27:23)
> [GCC 4.1.1 20060525 (Red Hat 4.1.1-1)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> 
>>>>def foo():
> 
> ...     x = 2
> ...
> 
>>>>foo()
>>>>def bar():
> 
> ...     x[2] = 2
> ...
> 
>>>>bar()
> 
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "<stdin>", line 2, in bar
> NameError: global name 'x' is not defined
> 
> Thanks,
> Jianbing
> 

1. Each function call creates its own namespace, so "x" in foo() is 
"isolated" from the global namespace or from calls of bar().
2. Think of assignment as assigning a name to a value rather than 
"putting a value" into the name. When you assign, you completely change 
the identity of name, rather than changing the contents of the name.

For example:


py> x = object()
py> id(x)
1074201696
py> x = object()
py> id(x)
1074201704

Notice how the identity (id) of x changes.

James



More information about the Python-list mailing list