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

Arnaud Delobelle arnodel at gmail.com
Wed Sep 28 07:23:42 CEST 2011

On 28 September 2011 01:56, Bruce Leban <bruce at leapyear.org> wrote:
> I proposed a special decorator-like syntax ($inject) which would pull the
> declaration out of the function entirely (putting it at the scope where it
> evaluates). There wasn't much discussion other than that it wasn't feasible
> with current implementation.

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

def foo(x):
    own i
    i += 1
    return i


More information about the Python-ideas mailing list