[Python-ideas] Allow lambda decorators

Chris Rebert pyideas at rebertia.com
Mon Feb 9 07:02:49 CET 2009

On Sun, Feb 8, 2009 at 9:40 PM, Aahz <aahz at pythoncraft.com> wrote:
<much snippage>
> Maybe I've been corrupted by the functional mindset (I hope not!), but I
> can follow this.  As Carl says, the key is to focus on the scoping
> problem:
> def func_maker():
>    fs = []
>    for i in range(10):
>        def f():
>            return i
>        fs.append(f)
>    return fs
> This creates a list of function objects, but the way scoping works in
> Python, every single function object returns 9 because that's the final
> value of ``i`` in func_maker().  Living with this wart is an option;
> changing Python's scoping rules to fix the wart is probably not worth
> considering.  Carl is suggesting something in-between, allowing the use
> of lambda combined with decorator syntax to create an intermediate scope
> that hides func_maker()'s ``i`` from f().
> I think that's ugly, but it probably is about the best we can do -- the
> other options are uglier.

This will likely get shot down in 5 minutes somehow, but I just want
to put it forward since I personally didn't find it ugly: Has a
declaration been considered (like with `nonlocal`)? Seems a relatively
elegant solution to this problem, imho. I know it was mentioned in a
thread once (with the keyword as "instantize" or "immediatize" or
something similar), but I've been unable to locate it (my Google-chi
must not be flowing today).

The basic idea was (using the keyword "bind" for the sake of argument):

def func_maker():
    fs = []
    for i in range(10):
        def f():
            bind i #this declaration tells Python to grab the value of
i as it is *right now* at definition-time
            return i
    return fs

The `bind` declaration would effectively tell Python to apply an
internal version of the `lambda x=x:` trick/hack/kludge automatically,
thus solving the scoping problem.

I now expect someone will point me to the thread I couldn't find
and/or poke several gaping holes in this idea.


Follow the path of the Iguana...

More information about the Python-ideas mailing list