Using lambda [was Re: Article of interest: Python pros/cons for theenterprise]

Duncan Booth duncan.booth at invalid.invalid
Mon Feb 25 10:12:23 EST 2008


Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> wrote:

> On Sun, 24 Feb 2008 21:13:08 -0500, Terry Reedy wrote:
> 
>> | I even use "named anonymous functions" *cough* by assigning lambda 
|
>> functions to names:
>> |
>> | foo = lambda x: x+1
>> 
>> Even though I consider the above to be clearly inferior to
>> 
>> def foo(x): return x+1
>> 
>> since the latter names the function 'foo' instead of the generic
>> '<lambda>'.
> 
> Absolutely. If foo() was a function that the user would see, I would 
> certainly use the def form to create it.
> 
> But in a situation like this:
> 
> 
> def parrot(x, y, z, func=None):
>     if func is None:
>         func = lambda x: x+1
>     return func(x+y+z)
> 
> 
> I don't see any advantage to writing it as:
> 
> def parrot(x, y, z, func=None):
>     if func is None:
>         def func(x): return x+1
>     return func(x+y+z)
> 
> 
> 
I take it you never feel the need to inspect tracebacks, nor insert a 
breakpoint or print statement at an arbitrary point in the code.

Granted none of those may apply in this particular simple case, but if 
you pass functions/lambdas around a lot it can be frustrating when you 
get an error such as:

    TypeError: <lambda>() takes exactly 2 arguments (1 given)

and the traceback only tells you which line generated the TypeError, not 
which lambda was involved. On the other hand:

    TypeError: parrot_func() takes exactly 2 arguments (1 given)

while it might not identify the function uniquely in all situations at 
least tells you something useful about the function being called.




More information about the Python-list mailing list