annonymous functions -- how to

Peter Hansen peter at engcorp.com
Thu May 5 07:45:33 EDT 2005


Jason Mobarak wrote:
> What's wrong with:
> 
> def blah():
>   def _ (a, b, c):
>     a = a + 2
>     print "stmt 2"
>     return a+b/c
>   return doSomethingWith(_)
> 
> It's basically "anonymous", it just uses a name that you don't care
> about. AFAIK, it can be immediately clobbered later if need be.
> Otherwise, the function shouldn't be anonymous.

Or even better:

def blah():
    def doJasonsAlgorithm(a, b, c):
       a = a + 2
       print "stmt 2"
       return a+b/c
    return doSomethingWith(doJasonsAlgorithm)

That way you've got reasonably self-documenting code, and don't have to 
face an annoyed maintainer saying "what a jerk: he didn't comment this 
or even give it a useful name... idiot... grumble grumble."

I doubt there's a valid usecase for a "anonymous" function that has more 
than a line or two.  Personally, I don't think there's a good usecase 
for an anonymous function longer than one line...

-Peter



More information about the Python-list mailing list