Code block literals

Dave Benjamin dave at 3dex.com
Wed Oct 8 23:29:09 CEST 2003


Alex Martelli wrote:
> The only annoyance here is that there is no good 'literal' form for
> a code block (Python's lambda is too puny to count as such), so you
> do have to *name* the 'thefunc' argument (with a 'def' statement --
> Python firmly separates statements from expressions).

Here's my non-PEP for such a feature:

return { |x, y|
     print x
     print y
}

Which would be the equivalent of:

def anonymous_function(x, y):
     print x
     print y
return anonymous_function

It's unambiguous because no dictionary literal would ever start with 
'{|', it looks almost identical to a certain other language <g>, and 
instead of being a special case for a function, it would just be a plain 
old HOF. No more talk of puny lambda:, and we can all go home and 
happily write visitor patterns and event callbacks all day long.

Then, merge map, filter, and reduce into the list type, so we can play 
Smalltalk and write stuff like:

 >>> print mylist.map({ |x| return x + 2 }, range(5))
0, 2, 4, 6, 8

If you wanted to span multiple lines, just take the first indentation 
you find and start from there:

closure = True
some_screen_object.on_click = { |e|
     print 'got an event: ' + e
     handle_screen_object_click()
     if closure = True:
         go_home_happy()
}

You're welcome,
Dave ;)





More information about the Python-list mailing list