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

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Mon Feb 25 10:34:57 EST 2008


On Mon, 25 Feb 2008 15:12:23 +0000, Duncan Booth wrote:

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


Nah, my code is always perfect, first time, every time.

*wink*
 
> Granted none of those may apply in this particular simple case, 

This sort of simple case is the one where I would use lambda.


> 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:

In the simple cases I'm talking about, there is only one lambda in scope 
at a time. If that were not the case, I'd use def.

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

Sure. For a more complicated case where I'm passing the function around a 
lot, def is the way to go. Likewise if the function is complex, I'd use 
def instead of trying to cram the whole algorithm into a single 
expression for lambda.

I'm not saying that I never use nested def, only that I sometimes assign 
lambdas to names. And why not? A lambda function is a first class object 
like everything else :)


-- 
Steven



More information about the Python-list mailing list