explain this function to me, lambda confusion

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri May 9 01:12:17 EDT 2008


En Thu, 08 May 2008 22:57:03 -0300,  
<andrej.panjkov at climatechange.qld.gov.au> escribió:

> On May 8, 6:11 pm, Duncan Booth <duncan.bo... at invalid.invalid> wrote:
>
>> No, no, no, no, no!
> Geez.  Go easy.
>> You have got it entirely wrong here. Your XOR function simply
[...]
> Pardon my tetchiness, but it is a little hard to receive such blunt
> and inflexible replies to my posts.

Don't take it so seriously. I would have written a reply in the same tone.  
Weeds must be uprooted early :)

> Both the responses offer lambda free alternatives.  That's fine, and
> given the terse documentation and problems that I had understanding
> them, I would agree.  So what applications are lambdas suited to?  I
> think the parameterised function model is one.
> What else?

It should be clear now that lambda is just a shortcut for defining a  
normal function using "def", except it has no name, and it can handle  
expressions only (no statements).
So you never *need* a lambda. But in a few cases they're useful:

- Most GUIs are event-driven, and let you bind a function (or any other  
callable object) to be executed when certain event happens (by example,  
when certain button is pressed, or a menu item is selected). Usually an  
instance method is used: Button("Total", onclick=self.calculate_total).  
Suppose you're developing a calculator; the ten buttons labeled '0' to '9'  
should inserte the corresponding digit. To do that, you should write ten  
functions insert_digit_0 to insert_digit_9 (and they would be  
one-line-functions: insert_digit('0') ... insert_digit('9')). Too boring :(
The usual idiom is something like this:
     Button("0", onclick=lambda: self.insert_digit('0'))
     Button("5", onclick=lambda: self.insert_digit('5'))

- To write an expression that is to be evaluated lazily (perhaps only if  
certain other conditions are met). Older Python versions didn't have a  
conditional expression like C's :? ternary operator, and one possible way  
to emulate it is this:

def iif(cond, if_true, if_false):
     if cond:
         return if_true()
     else:
         return if_false()

iff(x!=2, lambda: 1/(x-2), lambda: 100)

You can't write iff(x!=2, 1/(x-2), 100) because arguments are evaluated  
before the function is called, and with x=2 you get an error.

-- 
Gabriel Genellina




More information about the Python-list mailing list