One of the nice things about lambda
that's in my opinion understated is that it's way of deferring an evaluation for simple forms till the value is needed. Let me explain.
Many library routines are implemented so that they allow certain parameters to be callables (of whom lambda is one). The idea is that the actual value will be computed only at the time when it's going to be used (rather that when it's called). An (contrived) example might help to illustrate the point. Suppose you have a routine which which was going to do log a given timestamp. You want the routine to use the current time minus 30 minutes. You'd call it like so
log_timestamp(datetime.datetime.now() - datetime.timedelta(minutes = 30))
Now suppose the actual function is going to be called only when a certain event occurs and you want the timestamp to be computed only at that time. You can do this like so
log_timestamp(lambda : datetime.datetime.now() - datetime.timedelta(minutes = 30))
Assuming the log_timestamp
can handle callables like this, it will evaluate this when it needs it and you'll get the timestamp at that time.
There are of course alternate ways to do this (using the operator
module for example) but I hope I've conveyed the point.
Update: Here is a slightly more concrete real world example.
Update 2: I think this is an example of what is called a thunk.