[Python-ideas] nonlocal functions
MRAB
python at mrabarnett.plus.com
Tue Oct 20 18:00:51 CEST 2009
Bruce Leban wrote:
> On Tue, Oct 20, 2009 at 4:04 AM, Nick Coghlan <ncoghlan at gmail.com
> <mailto: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:
>
I'd prefer:
def foo():
a = 1
b = 3
def bar():
nonlocal *
local b
a = 2
b = 4
return (a,b)
if a later 'local' can override an earlier 'nonlocal', or:
def foo():
a = 1
b = 3
def bar():
local b
nonlocal *
a = 2
b = 4
return (a,b)
if a 'nonlocal' can act as a catch-all for any names not previously
mentioned.
More information about the Python-ideas
mailing list