[Python-ideas] nonlocal functions

Bruce Leban bruce at leapyear.org
Tue Oct 20 17:28:16 CEST 2009


On Tue, Oct 20, 2009 at 4:04 AM, Nick Coghlan <ncoghlan at gmail.com> wrote:

> The difference lies in the fact that in C, object references are
> non-local by default - you have to declare them explicitly in the
> current scope to make them local.
>
> Accordingly, I find the idea of a new function-like construct where all
> non-argument variable references are nonlocal by default to be a
> potentially interesting one.
>

Hmm. That's an interesting idea.

I don't know enough about internals. It might be possible to do this with a
decorator

def foo():
    a = 1
    @allnonlocal
    def bar():
        a = 2
    bar()
    return a

foo() => 2

However, even if possible, that would make everything nonlocal with no way
to pick which ones. Here's another idea:

def foo():
    a = 1
    b = 3
    nonlocal def bar():
        local b
        a = 2
        b = 4
    return (a,b)

foo() => (2, 3)

Prepending nonlocal to a function definition is equivalent to applying
nonlocal to every variable referenced in that function unless the variable
is declared local. For backward compatibility, the local statement would
only be only recognized inside nonlocal functions. (Thus if you have a
function that uses 'local' as a variable it would not need to be changed
unless you decided to stick nonlocal in front of it.)

Alternative syntax:
    def bar() nonlocal:

--- Bruce
http://www.vroospeak.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20091020/c5e12b6b/attachment.html>


More information about the Python-ideas mailing list