[Python-Dev] anonymous blocks

Guido van Rossum gvanrossum at gmail.com
Tue Apr 19 20:55:02 CEST 2005


> (I apologize that this is my first post.  Please don't flame me into
> oblivion or think I'm a quack!)

(Having met JJ I can assure he's not a quack. But don't let that stop
the flames. :-)

> Have you guys considered the following syntax for anonymous blocks?  I
> think it's possible to parse given Python's existing syntax:
> 
>    items.doFoo(
>        def (a, b) {
>            return a + b
>        },
>        def (c, d) {
>            return c + d
>        }
>    )
> 
> Notice the trick is that there is no name between the def and the "(",
> and the ")" is followed by a "{".
> 
> I understand that there is hesitance to use "{}".  However, you can
> think of this as a Python special case on the same level as using ";"
> between statements on a single line.  From that perspective, it's not
> inconsistent at all.

It would be a lot less inconsistent if {...} would be acceptable
alternative block syntax everywhere.

But what exactly are you trying to accomplish here? I think that
putting the defs *before* the call (and giving the anonymous blocks
temporary local names) actually makes the code clearer:

def block1(a, b):
    return a + b
def block2(c, d):
    return c + d
items.doFoo(block1, block2)

This reflects a style pattern that I've come to appreciate more
recently: when breaking a call with a long argument list to fit on
your screen, instead of trying to find the optimal break points in the
argument list, take one or two of the longest arguments and put them
in local variables. Thus, instead of this:

self.disentangle(0x40,
                 self.triangulation("The quick brown fox jumps over
the lazy dog"),
                 self.indent+1)

I'd recommend this:

tri = self.subcalculation("The quick brown fox jumps over the lazy dog")
self.disentangle(0x40, tri, self.indent+1)

IMO this is clearer, and even shorter!

If we apply this to the anonymous block problem, we may end up finding
lambda the ultimate compromise -- like a gentleman in the back of my
talk last week at baypiggies observed (unfortunately I don't know his
name).

-- 
--Guido van Rossum (home page: http://www.python.org/~guido/)


More information about the Python-Dev mailing list