del operator and global namespace

A

alust

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?
 
M

MRAB

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top