what is lambda used for in real code?

Jeff Shannon jeff at ccvcorp.com
Mon Jan 3 15:06:49 EST 2005


Steven Bethard wrote:

> The only ones that make me a little nervous are examples like:
> 
> inspect.py: def formatargspec(args, varargs=None, varkw=None,
>                   ...
>                   formatvarargs=lambda name: '*' + name,
>                   formatvarkw=lambda name: '**' + name,
>                   formatvalue=lambda value: '=' + repr(value),
> 
> where the lambdas are declaring functions as keyword arguments in a def. 

At least in this case, a number of these can be handled with curry / 
partial(), I think --

     ...
     formatvarargs = partial(operator.add, '*'),
     formatvarkw = partial(operator.add, '**'),
     ...

The last is a bit more complicated, since it's got an extra (deferred) 
function call, so I'm not sure exactly how to deal with that cleanly.

Actually, in this specific case, since these are all creating strings, 
it'd be pretty trivial to simply do this manipulation inside of the 
function body rather than inside of the arglist:

     def formatargspec(..., formatvarargs,
                            formatkwargs,
                            formatvalue, ...):
         formatvarargs = '*' + formatvarargs
         formatvarkw = '**' + formatvarkw
         formatvalue = '=' + repr(value)

This has the disadvantage of having names typed multiple times, which 
is definitely a minus, but it's arguably a bit more clear to 
explicitly manipulate the strings within the function body rather than 
burying that manipulation somewhere in the argument list.  Personally 
I'd call this a wash, though I expect that others will disagree with 
me. ;)  And whatever the merits of this particular case, similar cases 
may not be so easy to avoid in this fashion...

Jeff Shannon
Technician/Programmer
Credit International




More information about the Python-list mailing list