Let's Talk About Lambda Functions!

Steve Holden sholden at holdenweb.com
Sat Jul 27 00:12:30 EDT 2002


"Alex Martelli" <aleax at aleax.it> wrote in message
news:41j09.125397$Jj7.2891527 at news1.tin.it...
> Robb Shecter wrote:
>
> > But to really answer you - I like lambdas and think lambdas can add
> > clarity because their scope directly reflects their 'scope'.  (Make
> > sense?)
>
> Sorry, not to me.  Take a typical bug sometimes posted here, such as:
>
> 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.

> 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).

>
> Using a closure instead of the lambda:
>
> def makeprinter(word):
>     def printword(): print word
>     return printword
>
> for word in 'fee fie foo fum'.split():
>     Button(frame, command=makeprinter(word))
>
> is one of several ways to make the bug disappear (another is to
> use a "lambda word=word: print word" snapshot-trick, but that
> seems to fly in the face of your liking lambda's "scope"...?).
> Closures' "scopes" can be said to directly reflect what they
> should reflect.  I can't see how you can claim this for lambda.
>

not-like-you-to-propagate-syntax-errors-ly y'rs  - steve
-----------------------------------------------------------------------
Steve Holden                                 http://www.holdenweb.com/
Python Web Programming                http://pydish.holdenweb.com/pwp/
-----------------------------------------------------------------------








More information about the Python-list mailing list