Let's Talk About Lambda Functions!
Alex Martelli
aleax at aleax.it
Sat Jul 27 03:21:57 EDT 2002
Steve Holden wrote:
...
>> for word in 'fee fie foo fum'.split():
>> Button(frame, command=lambda: print word)
>>
>> The poster is typically nonplusses that all buttons print 'fum'.
>>
> I would be nonplussed if that code even *compiled*, given that "print" is
> a keyword and lambda takes an expression not a statement.
Right - you caught my little trap. I don't regret using it, though,
because it DID catch a couple of lambda-lovers... and it also shows
a real issue with lambda. Sure, you get a SyntaxError and that's
that. But if you want to use lambda, you have to keep dismantling
and restructuring to change to def'd functions each time you need a
statement there (and print is a good example here, as it does help
debugging).
>> Lambda's scope (or 'scope') has taken another victim.
>>
> This is not to say, of course, that newbies don't try to write exactly
> such incorrect code, and this is probably one of the reasons why Guido
> continues to suggest it's a wart (albeit one we're going to have to
> continue to live with).
I think the reason why Guido suggests it's a wart is that it IS a wart.
Sure, backwards compatibility mandates lambda stay, but I think it's
worth emphasizing that it's there ONLY for backwards compatibility,
and using def is better.
> not-like-you-to-propagate-syntax-errors-ly y'rs - steve
Right. Inserting subtle traps in my examples, however, IS a think
I've been known to do. Sometimes it helps drive a point home.
Alex
More information about the Python-list
mailing list