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

Nick Coghlan ncoghlan at gmail.com
Mon Sep 26 21:57:02 CEST 2011

On Mon, Sep 26, 2011 at 12:27 PM, Bruce Leban <bruce at leapyear.org> wrote:
> The keyword nonlocal means that this binding is not local to this scope but
> can be found up the call stack. In contrast, your usage means the binding is
> local to this function, created before the function is called the first time
> and shared with all calls to this function. Those are orthogonal scopes.

See my reply to Paul - while I agree that visibility and lifetime are
different aspects of named references, it isn't like they're
independent. A nonlocal reference from an inner function has a direct
effect on the lifecycle of an otherwise local variable in the outer

Consider the following two functions:

    def f():
        x = 0
        return x

Here, 'x' is an ordinary local variable - it only exists while the
frame is executing.

    def f():
        x = 0
        def inner():
            nonlocal x
            x += 1
            return x
        return inner

Now, the use of 'nonlocal' in the inner function has *changed the
lifecycle* of x. It is now a nonlocal variable - it survives beyond
the execution of the function that defines it. Paul was quite right to
point out that most developers only think about the visibility aspect
of 'nonlocal', since they're looking at the impact from the point of
view of the inner function, but that doesn't mean the lifecycle impact
on the outer function that I want to highlight is arbitrary or


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list