a little trap revealed (was Re: Let's Talk About Lambda Functions!)

Gerald Squelart squelart at hotmail.nospam.com
Sun Jul 28 02:58:29 EDT 2002


"Daniel Fackrell" <unlearned at learn2think.org> wrote
> On Sat, 27 Jul 2002 23:50:01 -0600, Gerald Squelart wrote:
> > "Erik Max Francis" <max at alcyone.com> wrote
> >> Michele Simionato wrote:
> >> > I know a print statement cannot stay in a lambda function, however as
> >> > a newbie I ask : why ?
> >> Because a lambda is an expression, not a statement.
> > Therefore, a lambda *expects* an expression, not a statement.
> >
> > However, you could indirectly include a print statement in the course of
> > a running lambda expression:
> > def printArg(arg):
> >     print arg
> >     return arg
> > l = lambda x: printArg(x)
> > a = l(10) # will print 10 and assign 10 to a map(l, range(5)) # will
> > print numbers 0 to 4 and return [0, 1, 2, 3, 4] It may be useful to
> > debug a lamdba expression.
>
> Correct me if I'm wrong, but doesn't this just create an anonymous
> function that calls the named function printArg?  Besides the added
> function-call overhead, how are the two following lines functionally
> different?
>
> l = lambda x: printArg(x)
> l = printArg
>
> Daniel Fackrell

Yeah, that was a very simple expression, to show how it could work... Of course this
lambda function is pretty lame!

Well, my point was: if you have a lambda function used like this:
map(lambda x: big_expression, some_list)
and now you want to print something from the anonymous function, then it's possible
by just adding the stoopid printArg() function around some subexpression, without
having to remove the complete lambda expression and replacing it by a function def
and a call...
You choose:
def lambdaReplacement(x):
    print stuff
    return big_expression
map(lambdaReplacement, some_list)
- or -
def printArg(x):
    print x
    return x
map(lambda x: expression_with_printArg, some_list)

And it's easier to remove later, if needed, methinks

Of course, some think lambda is inherently evil, I can't argue with that, it's a
matter of taste...
Let's not start this war please ;-)

G.





More information about the Python-list mailing list