behavior difference for mutable and immutable variable in function definition

Roger Miller roger.miller at nova-sol.com
Fri May 4 21:03:58 EDT 2007


On May 4, 12:39 pm, 7stud <bbxx789_0... at yahoo.com> wrote:
> On May 4, 3:30 pm, jianbing.c... 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
>
> The first function is completely irrelevant unless you expect this to
> work:
>
> x = 2
> x[2] = 2
>
> Traceback (most recent call last):
>   File "test1.py", line 2, in ?
>     x[2] = 2
> TypeError: object does not support item assignment
>
> So that leaves you with:
>
> > >>> def bar():
>
> > ...     x[2] = 2
> > ...
>
> > >>> bar()
>
> Would you expect this to work:
>
> x[2] = 2
> print x

I will sympathize with the OP to the extent that the message "global
name 'x' is not defined" is a bit misleading. All that the interpreter
really knows is that 'x' is not defined, locally or globally, and it
should probably not presume to guess the coder's intention.





More information about the Python-list mailing list