lambda expressions
Fernando Pérez
fperez528 at yahoo.com
Sun Feb 3 08:41:52 EST 2002
Gerson Kurz wrote:
> And, of course, my examples were not taken "from real life". There is
> however one nice usage of lambda: passing context.
[snip]
Quick comment. I actually need this frequently precisely for numerical
methods, but prefer to use the alternate approach of writing the context-part
as extra arguments. The reason is that the lambda approach generates an extra
nested function call for each of your original function calls, and in a
numerical algorithm this can be very expensive (particularly considering how
expensive function calls are in Python).
A quick example:
#-----------------------------------------------------------------------------
def constrained_svdfit(x,y,sig,fix_i,fix_v,funcs,*args,**kw):
# this will be a (num_params X num_datapts) matrix
phi_base=funcs(x,*args,**kw)
[ snipped rest of code...]
Here, funcs is a function that returns a set of fit functions evaluated at
the array of input data x. All extra context is passed to funcs via *args and
**kw. If on top of that I also want constrained_svdfit() to take keyword
args, I just set up a naming convention so that they all begin with _svd_ or
something similar, and strip them from the **kw dict before passing it to
funcs().
Cheers,
f
PS. If by any chance the actual code is of interest to you, just email me. I
removed the numerical details from this post but the above is taken from
actual working code.
More information about the Python-list
mailing list