[Python-il] [pyweb-il:1072] Python coding question

cool-RR cool-rr at cool-rr.com
Wed Jan 26 12:18:01 IST 2011

On Fri, Jul 9, 2010 at 1:49 AM, Shai Berger <shai at platonix.com> 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
    del x

This is now allowed. Remember that the target of an
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>
Python 3.1 and now works again:

def f():
    def print_error():
    except Exception as e:
       # implicit "del e" here

(See issue 4617 <http://bugs.python.org/issue4617>.)

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://hamakor.org.il/pipermail/python-il/attachments/20110126/a79b959e/attachment.htm>

More information about the Python-il mailing list