[Python-ideas] Allow lambda decorators

Aahz aahz at pythoncraft.com
Mon Feb 9 06:40:26 CET 2009

On Sun, Feb 08, 2009, Guido van Rossum wrote:
> On Sun, Feb 8, 2009 at 4:41 PM, Carl Johnson <carl at carlsensei.com> wrote:
>> >>> def each_in(seq):
>> ...     return lambda f: lambda: [f(item) for item in seq]
>> ...
>> >>> def func_maker():
>> ...     @each_in(range(10))
>> ...     def fs(i):
>> ...         def f():
>> ...             return i
>> ...         return f
>> ...     return fs() #Warning, fs is a function, not a list
>> ...
>> >>> [f() for f in func_maker()]
>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
> I'm sorry, but you are using two nested lambdas plus a list
> comprehension, and three nested functions here, plus one more list
> comprehension for showing the result. My brain hurts trying to
> understand all this. I don't think this bodes well as a use case for a
> proposed feature.
> I'm not trying to be sarcastic here -- I really think this code is too
> hard to follow for a motivating example.

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

def func_maker():
    fs = []
    for i in range(10):
        def f():
            return i
    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.  

What I don't know is whether it's worth considering; abusing scope is not
generally considered Pythonic, but we've been slowly catering to that
market over the years.  Given my general antipathy to decorators as
obfuscating code, I don't think Carl's suggestion causes much damage.

Carl, let me know if I've accurately summarized you.
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

Weinberg's Second Law: If builders built buildings the way programmers wrote 
programs, then the first woodpecker that came along would destroy civilization.

More information about the Python-ideas mailing list