Is this a good use for lambda
fredrik at pythonware.com
Mon Dec 20 07:43:43 CET 2004
Bengt Richter wrote:
>>Ahem. If you name the function, you can reuse the name (or just forget about it)
>>as soon as you've used the function object.
>>If you don't want to reuse the name because you might want to reuse the function
>>object, you have to name it anyway.
> Are you forgetting that all bindings are not directly name bindings as created by def? ;-)
> (See also various tkinter-related uses).
> >>> funs = [lambda:'one', lambda:'two', lambda:'three']
now you've used the function objects once each.
> >>> for use in xrange(2):
> ... for i in xrange(3):
> ... print '%susing fun[%s] => %r' %('re'*(use>0), i, funs[i]())
and now you're using the data structure you built... at this point, it doesnt matter
if the functions had distinct names to start with.
(coming up with a contrived example where it matters is trivial, of course, but by
then, we've moved into "whitespace" or "static typing leads to more reliable code"
More information about the Python-list