Why anonymity? [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey]

Duncan Booth duncan.booth at invalid.invalid
Thu Jul 7 05:36:24 EDT 2005


Steven D'Aprano wrote:
> This is something I've never understood. Why is it bad 
> form to assign an "anonymous function" (an object) to a 
> name?

Because it obfuscates your code for no benefit. You should avoid making it 
hard for others to read your code (and 'others' includes yourself in the 
future).

Also, it obfuscates tracebacks: all lambda expressions will identify in 
tracebacks as <lambda>, but if you define a function you can give it a 
meaningful name.

> 
> Why is it considered abuse of lambda to assign the 
> functions to a name? Is it an abuse of lambda to do this?
> 
> D = {"one": lambda noun: noun,
>      "two": lambda noun: noun + 's',
>      "many": lambda noun: 'lots of ' + noun + 's' }
> 
> assert D["two"]("python") == "pythons"
> 
> 
No, that is approaching a reasonable use of lambda, however I would still 
be inclined to write it with functions. e.g.

   def one(noun):
       return noun

   def two(noun):
       return noun+'s'

   def many(noun):
       return 'lots of %ss' % (noun,)

   D = dict(one=one, two=two, many=many)

although in this particular case I would probably just put format strings 
in the dictionary:

  def D(style, noun):
     formats = dict(one="%s", two="%ss", many="lots of %ss")
     return formats.get(style, "an indeterminate number of %ss") % (noun,)

  assert D("two","python") == "pythons"



More information about the Python-list mailing list