[Python-ideas] nonlocal functions
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
a = 1
a = 2
foo() => 2
However, even if possible, that would make everything nonlocal with no way
to pick which ones. Here's another idea:
a = 1
b = 3
nonlocal def bar():
a = 2
b = 4
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.)
def bar() nonlocal:
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas