6

From the Python Language Reference (v 3.1, see here - http://docs.python.org/py3k/reference/executionmodel.html#naming-and-binding ):

It is illegal to unbind a name referenced by an enclosing scope; the compiler will report a SyntaxError.

But when I run the following code:

a = 3

def x():
  global a
  del(a)

print(a)
x()

it works fine; and when I change the order of calls:

x()
print(a)

I get a NameError, not a SyntaxError. Apparently, I'm not understanding the rule correctly. Can anyone explain it? Thanks.

  • Can you link to where you quote? This page says a NameError should be raised: http://docs.python.org/py3k/reference/simple_stmts.html#the-del-statement – carl Feb 20 '11 at 09:20
  • @carl: Took me a few to find it too; several paragraphs into http://docs.python.org/py3k/reference/executionmodel.html#naming-and-binding. – Fred Nurk Feb 20 '11 at 09:24
  • Added the link to the appropriate section of the language reference. –  Feb 20 '11 at 09:29

2 Answers2

4

I don't think that rule applies to the global scope. The global scope is always fully accessible.

Here's an example:

>>> def outer():
...     a=5
...     def inner():
...         nonlocal a
...         print(a)
...         del a
...
SyntaxError: can not delete variable 'a' referenced in nested scope
AndiDog
  • 68,631
  • 21
  • 159
  • 205
3

I contacted the people on python-devel list and here is what I got:

Actually you can do that now 3.2+. I've now removed that sentence.

So, actually it was sort of a documentation error.