Let's Talk About Lambda Functions!

Alex Martelli aleax at aleax.it
Fri Jul 26 17:18:56 EDT 2002


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

Lambda's scope (or 'scope') has taken another victim.


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.


Alex




More information about the Python-list mailing list