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

Guido van Rossum guido at python.org
Wed Sep 28 00:32:43 CEST 2011

On Tue, Sep 27, 2011 at 3:24 PM, Arnaud Delobelle <arnodel at gmail.com> wrote:
> 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.

Yes, you have a point. Hiding side effects this way could be nasty,
and this is actually the first point in favor of the default argument
hack I've heard in a while. :-)

C++ has special syntax to force the programmer to write certain things
after the argument list but before the function body (I think only for
constructors). I have seen too many constructors with a short argument
list, a very short body, and a ton of code cramped in between, to like
the idea very much: even though it is semantically something totally
different, syntactically it would have the same awkwardness.

--Guido van Rossum (python.org/~guido)

More information about the Python-ideas mailing list