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

Jacob Holm jh at improva.dk
Wed Sep 28 11:27:45 CEST 2011

On 2011-09-28 07:23, Arnaud Delobelle wrote:
> A hybrid approach would be possible, taking from both approaches
> (decorator and keyword):
> * a keyword to declare in the body of the function that a variable is
> of the "own" kind.
> * function objects would grow an __own__ attribute which is a dict-like object:
>     - f.__own__["i"] would return the contents of the cell that the
> own variable "i" refers to
>     - f.__own__["i"] = 42 would set the cell contents of the own
> variable "i" to 42
> (or some other equivalent mechanism)
> * then one could create a kind of "inject" decorator.
> Here's an example:
> def setown(**kwargs):
>     def decorator(f):
>         for k, v in kwargs.items():
>             f.__own__[k] = v
>     return decorator
> @setown(i=42)
> def foo(x):
>     own i
>     i += 1
>     return i

I like this idea, but I think we should at least consider using
"nonlocal" instead of "own" as the keyword (and __nonlocal__ instead of
__own__ for the dict-like object).

- No new keyword needed, just a change in how "nonlocal x" is treated
when there is no 'x' variable in the defining scope.  (Today this is a

- No way to define an "own" variable with the same name as a variable in
the defining scope.
- Ambiguity as to exactly what the lifetime of the nonlocal is.  (If an
outer function with no "x" variable in scope defines two inner functions
that both use "nonlocal x", do they see the same "x"?)

Ok, so I don't actually like repurposing nonlocal for this.

+1 to your "own" suggestion.

- Jacob

More information about the Python-ideas mailing list