Securing a future for anonymous functions in Python

Ian Bicking ianb at
Thu Dec 30 20:07:39 CET 2004

John Roth wrote:
> The syntax I prefer (and I don't know if it's actually been
> suggested before) is to use braces, that is { and }.
> In other words, an anonymous function looks like:
>    {p1, p2, p3 |
>      stmt1
>      stmt2
>     }

What's the advantage of something like that over the non-anonymous 

def some_func(p1, p2, p3):

I appreciate some of the motivation, but merely avoiding giving 
something a name doesn't seem like a laudible goal.

The one motivation I can see for function expressions is 
callback-oriented programming, like:

     when_retrieved={page |

The problem with the normal function in this case is the order of 
statements is reversed:

   def when_retrieved_callback(page):
   get_web_page(url, when_retrieved=when_retrieved_callback)

Oh, and you have to type the name twice, which is annoying.  For most 
other functional programming constructs, list (and not generator) 
comprehensions work well enough, and the overhead of naming functions 
just isn't that big a deal.

I think this specific use case -- defining callbacks -- should be 
addressed, rather than proposing a solution to something that isn't 
necessary.  Which is to say, no one *needs* anonymous functions; people 
may need things which anonymous functions provide, but maybe there's 
other ways to provide the same thing.  Decorator abuse, for instance ;)

   def get_web_page_decorator(url):
       def decorator(func):
           return get_web_page(url, when_retrieved=func)
       return decorator

   def when_retrieved(page):

Or even (given a partial function as defined in some PEP, the number of 
which I don't remember):

   @partial(get_web_page, url)
   def when_retrieved(page):

It's okay not to like this proposal, I don't think I'm really serious. 
But I do think there's other ways to approach this.  Function 
expressions could get really out of hand, IMHO, and could easily lead to 
  twenty-line "expressions".  That's aesthetically incompatible with 
Python source, IMHO.

Ian Bicking  /  ianb at  /

More information about the Python-list mailing list