Deleting variables referenced in nested scope

Hans Nowak wurmy at earthlink.net
Sat Dec 22 03:36:18 CET 2001


Jesse W wrote:
> 
>         As I was playing arround with the new nested scopeing rules in
> Python 2.2a2, I got a SyntaxError I did not understand.  Here is the
> code:
> 
> def foo():
>     x=5
>     add=lambda a:x+a
>     del x
> 
> When I ran this, I got this error:
> 
> SyntaxError: can not delete variable 'x' referenced in nested scope
> 
> What is this error?  Why is it here?  What does it mean?

What it says: you are trying to delete a variable (x) that
is referenced in a nested scope, in this case, within the
lambda. Python functions (including lambdas) use dynamic
lookup for variables; IOW, when you call this function,
it will try to look for variable x, which lives in function
foo's namespace. If you delete it, as you are trying to do,
it won't be able to find it anymore. Hence the error.

At least, that's what I think. ;-)

--Hans



More information about the Python-list mailing list