Let's Talk About Lambda Functions!

John Roth johnroth at ameritech.net
Mon Jul 29 14:43:11 EDT 2002


"Steve Holden" <sholden at holdenweb.com> wrote in message
news:7Rc19.92310$724.23106 at atlpnn01.usenetserver.com...
> "John Roth" <johnroth at ameritech.net> wrote ...
> > "Fredrik Lundh" <fredrik at pythonware.com> wrote...
> >
> > What's the problem with that? If we give up the notion
> > that anonamous functions need to look like expressions,
> > it should be simple. Just stick the function definition inline,
> > indentation and all. The only issue is defining a new keyword,
> > since lambda doesn't work that way. "def" would probably
> > work, since it's only allowed at statement level now.
> >
> I'd like to see an example of this, since it appears you haven't fully
> thought this through. You mean you'd like to be able to write some
thing
> like the following:
>
>     for word in 'fee fie fo fum'.split():
>         Button(frame, command=lambda:
>             print word)
>
> This is currently acceptable in Python because the lambda's inside a
> parenthesised argument list. How would I add a second line to the
lambda?
> I'm always suspicious of phrasing like "all you need to do..." or "the
only
> issue...", since it often indicates that insufficient thought has gone
into
> a proposal. And the reason I'm suspicious when other people do it is
because
> I've watched me doing it enough to get into trouble!
>
> Conclusion: this idea is currently 0.345-baked :-)

    for word in 'fee fie fo fum'.split():
        Button(frame, command = def ():
                print word
            )

This isn't really the world's best example, because IMO, the
lambda form is easier to read for something this small. However,
it does give the guts of the idea:

1. instead of lambda (which needs to stay as is for backward
compatibility) it uses 'def' as the keyword.

2. The remainder of the syntax exactly models def, including
statement indentation within the expression. Notice that the
first statement in the anonamous function has to be indented
two from the preceeding line, because the continuation of
the expression has to still be indented from the line with the
'def', and dedented from the statements.

3. The use of 'def' here reflects a comment from one of
the posters that it's easy for people without experience in
languages with first class functions to miss the fact that Python
has them.

Hope this helps. I considered it simple enough that it really
didn't need an example.

John Roth






More information about the Python-list mailing list