lambda expressions

Gerson Kurz gerson.kurz at t-online.de
Sun Feb 3 11:28:57 EST 2002


On Sun, 3 Feb 2002 17:14:55 +0100, Bas van Gils <bas.vangils at home.nl>
wrote:

>Having read the recent thread on timing how fast code exectes, though, I
>wonder: are lambda-statments _faster_ ?

I think not, especially if the lambda-algorithm is more complicated
than the straightforward solution.

And, of course, my examples were not taken "from real life". There is
however one nice usage of lambda: passing context. 

Say, you have a convention that allows you to specify a callback
function, but no context to be passed to that function. For example,
say someone has written a newton-approximation function:
--------------
# newton-approximate function(x) in intervall range [start,stop]
def newton(function,start,stop):
	...
--------------
now, in this example "function" expects exactly one argument, x, so
"function" must look something like this:
--------------
def sample_function(x):
	# do something with x
...
newton(sample_function,0,pi)
--------------
If you want to pass context parameters to this function, lambda comes
in handy:
--------------
def sample_function(x,context):
	# do something with x given context
...
newton(lambda x:sample_function(x,context),0,pi)
--------------
the expression "lambda x:sample_function(x,context)" creates a new
function "on-the-fly", that will return the value of
sample_function(x,context). This is a very nice feature not found (or
rather: not easily worked around) in languages like C and C++ which
miss lambda:

If you know windows, you know WNDPROC, and you know that you cannot
easily pass context to a WNDPROC function. If you know linux, you know
signal(), and you know that you cannot easily pass context to a signal
handler. 




More information about the Python-list mailing list