Need help with understanding the following sentence from PEP 227 and the Python Language Reference
If a variable is referenced in an enclosed scope, it is an error to delete the name. The compiler will raise a SyntaxError for 'del name'.
Lack of examples caused I couldn't reproduce an error at compile time, so an explanation with examples is highly desirable.
The following raises the execption:
def foo():
spam = 'eggs'
def bar():
print spam
del spam
because the spam
variable is being used in the enclosed scope of bar
:
>>> def foo():
... spam = 'eggs'
... def bar():
... print spam
... del spam
...
SyntaxError: can not delete variable 'spam' referenced in nested scope
Python detects that spam
is being referenced in bar
but does not assign anything to that variable, so it looks it up in the surrounding scope of foo
. It is assigned there, making the del spam
statement a syntax error.
This limitation was removed in Python 3.2; you are now responsible for not deleting nested variables yourself; you'll get a runtime error (NameError
) instead:
>>> def foo():
... spam = 'eggs'
... def bar():
... print(spam)
... del spam
... bar()
...
>>> foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in foo
File "<stdin>", line 4, in bar
NameError: free variable 'spam' referenced before assignment in enclosing scope
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With