[Python-ideas] Tweaking closures and lexical scoping to include the function being defined

Arnaud Delobelle arnodel at gmail.com
Wed Sep 28 00:24:58 CEST 2011

On 27 September 2011 22:23, Guido van Rossum <guido at python.org> wrote:
> On Tue, Sep 27, 2011 at 2:04 PM, Arnaud Delobelle <arnodel at gmail.com> wrote:
>> On 27 September 2011 21:38, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
>> [...]
>>> As I remember, the idea foundered because it was thought
>>> too confusing to have an expression that was written
>>> inside the function but evaluated outside of it. If
>>> we're seriously considering the current proposal,
>>> presumably we've gotten over that? Or is it still a
>>> valid objection?
>> I have been reading this thread from the start and FWIW, it's
>> something that I have been feeling uncomfortable about.  I value the
>> guarantee that no code in the body of a def statement is executed when
>> the def statement itself is executed.  This proposal would break this
>> guarantee.
> That seems a guarantee made up specifically to prevent this proposal.

I wouldn't do this :)  I like new things.

> What benefit do you see from it?

It keeps things simple.  To be specific, when I read code I can "fold"
(mentally or with the help of a code editor) the body of a def
statement, knowing that I won't miss anything until the function is
called.  So the following won't raise:

    [some code]

    x = 42
    def foo():
        [I don't need to read the body]
    assert x == 42

But now def statements can have non-obvious side-effects.  For example:

    def spam_x():
        global x
        x = "spam"

    x = 42
    def foo():
        # Some body
        nonlocal y from spam_x()
        # More body
    assert x == 42

I may be unduly worrying about this, but it feels to me that it
lessens the overall tidiness of the language.  I would much rather
there was a way to initialise these "own" variables outside the body
of the function.


More information about the Python-ideas mailing list