del operator and global namespace
Dan Stromberg
drsalists at gmail.com
Wed Dec 8 13:52:00 EST 2010
Please try adding "global x" to the beginning of f().
On Wed, Dec 8, 2010 at 10:06 AM, alust <alust at alust.homeunix.com> 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?
>
> --
> Thanks, Alexei
> --
> http://mail.python.org/mailman/listinfo/python-list
>
More information about the Python-list
mailing list