[Python-ideas] Allow lambda decorators

Marcin 'Qrczak' Kowalczyk qrczak at knm.org.pl
Mon Feb 9 11:21:21 CET 2009


On Mon, Feb 9, 2009 at 07:02, Chris Rebert <pyideas at rebertia.com> wrote:

> 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
>        fs.append(f)
>    return fs

When is "now"? The bind, whatever it does, is not executed until the
function is called, which is too late. Letting it influence the
interpretation of f itself is confusing.

The problem stems from the fact that local variables are only local to
the enclosing function, without the possibility of finer scopes. If
variable declarations were explicit and scoped to the enclosing block,
this would work:

def func_maker():
    var fs = []
    for i in range(10):
        var j = i
        fs.append(lambda: j)
    return fs

or possibly even the original, depending on the semantics of for
(whether it binds a new variable on each iteration, scoped over the
body, or it rebinds the same variable each time).

-- 
Marcin Kowalczyk
qrczak at knm.org.pl
http://qrnik.knm.org.pl/~qrczak/



More information about the Python-ideas mailing list