del operator and global namespace

MRAB python at mrabarnett.plus.com
Wed Dec 8 13:32:14 EST 2010


On 08/12/2010 18:06, alust wrote:
> Hello,
>
> Can somebody explain this strange (to me) effect please.
>
> In this program it is impossible to access a global variable within a
> function:
>
> $ cat /tmp/test.py
> x='xxx'
> def f():
>       print x
>       del x
>
> f()
>
> $ python /tmp/test.py
> Traceback (most recent call last):
>     File "/tmp/test.py", line 6, in<module>
>       f()
>     File "/tmp/test.py", line 3, in f
>       print x
> UnboundLocalError: local variable 'x' referenced before assignment
>
> But if we comment the del operator the program will work:
>
> $ cat /tmp/test.py
> x='xxx'
> def f():
>       print x
>       #del x
>
> f()
>
> $ python /tmp/test.py
> xxx
>
> So why in this example the print operator is influenced by del
> operator
> that should be executed after it?
>
The Python source code is compiled to bytecodes which are then
interpreted. It's during the compilation stage that it determines
whether a name is local. If you bind to a name:

     x = 0

or del a name:

     del x

anywhere in the function, it takes that name to be local.

When it actually interprets the bytecode at the print statement it
tries to reference the name, but nothing has been bound to it yet, so
it raises an exception.



More information about the Python-list mailing list