any trick to allow anonymous code blocks in python?

John Roth newsgroups at jhrothjr.com
Sat Jun 26 07:36:39 EDT 2004


"Doug Holton" <insert at spam.here> wrote in message
news:ROydndnd54-eYUHdRVn_iw at comcast.com...
> John Roth wrote:
> >>Is there any metaclass trick or something similar to allow anonymous
> >>code blocks?
> >>
> ...
> > No. If you're looking for GUI callbacks, there's a significant
> > gap between lambdas and bound methods. You could
> > use something like (not tested):
> >
> > b.OnClick = (lambda : sys.stdout("You clicked me"))
>
> Yeah, I didn't mention the lambda option.  I was thinking about
> designing a framework meant for beginners, and I'd rather stay away from
> lambdas.  I'm surprised no one is even proposing support for anonymous
> code blocks in Python that support multiple lines, similar to what Ruby,
> Java, and other languages have.

It's been proposed a number of times, and you can find the
discussions (some of which amount to flame wars) by searching
Google Groups.

IIRC, there are two fundamental issues. One is syntax: it's not easy
to find a decent syntax that looks good, lets you shift back to statement
level from expression level, and handles blocks for each parameter
of a method.

The other issue is that blocks themselves don't do all that much.
Ruby's facility with blocks actually comes from the very nice
intersection of several features, including the pervasive implementation
of the visitor pattern in all collection objects and the provision of
a block as a special parameter. There are a couple of other
features that also help. Blocks without those other features
wouldn't do what Ruby does.

The same thing is true of, for example, Smalltalk. Blocks
have to be seen in the context of the entire language.

John Roth





More information about the Python-list mailing list