On Fri, Jul 9, 2010 at 1:49 AM, Shai Berger <[email protected]> wrote: > > [...] > > However, if that were the whole story, this code would raise a NameError: > > >>> def f(): > ... i=5 > ... def g(): return i > ... del i > ... return g > ... > >>> f()() > > In fact, the deletion of i in f is a syntax error, complaining about > deletion > of a variable. This is done because "If a name binding operation occurs > anywhere within a code block, all uses of the name within the block are > treated as references to the current block" > (http://docs.python.org/reference/executionmodel.html) -- that is, while > the > exact object bound to the name is looked up as late as possible, the scope > of > the name is set already at function definition (compilation) time. > > Thus, the nested function will only look for the current binding of i in > the > local namespace of its containing function; IMHO, this qualifies as a true > variable (though, true, it is not a constant place in memory). > > I hope this is still interesting to people here, > > Shai. >
Hey folks, The above syntax error that Shai pointed out really made an impression on me :) So it was funny when I saw a couple of days ago that Python 3.2 removes this syntax error <http://docs.python.org/dev/whatsnew/3.2.html>: Previously it was illegal to delete a name from the local namespace if it occurs as a free variable in a nested block: def outer(x): def inner(): return x inner() del x This is now allowed. Remember that the target of an except<http://docs.python.org/dev/reference/compound_stmts.html#except> clause is cleared, so this code which used to work with Python 2.6, raised a SyntaxError <http://docs.python.org/dev/library/exceptions.html#SyntaxError> with Python 3.1 and now works again: def f(): def print_error(): print(e) try: something except Exception as e: print_error() # implicit "del e" here (See issue 4617 <http://bugs.python.org/issue4617>.) Ram.
_______________________________________________ Python-il mailing list [email protected] http://hamakor.org.il/cgi-bin/mailman/listinfo/python-il
