[Python-ideas] Ruby-style Blocks in Python Idea

Greg Ewing greg.ewing at canterbury.ac.nz
Mon Mar 9 21:58:43 CET 2009

average wrote:

> MY point was really about how the programming art *itself* hasn't
> fully explored this concept to even be able to *evaluate* the power
> and usefulness of employing techniques such as code blocks.

On the contrary, I think Smalltalk has explored it very
well. Smalltalk implements *all* control structures in
terms of code blocks, and does so in a very readable
way, without any of the brain-exploding characteristics
of Lisp.

It works well in Smalltalk because the whole language
syntax is designed from the ground up to accommodate it.
Ruby inherits the idea, but struggles to fit it into its
syntax, leading to a much-weakened form (you can only
pass one code block to a given method at a time).

It's even harder to fit the idea into Python's syntax.
This isn't just because of the indentation issue, but
also because Pythonistas tend to have a higher standard
of aesthetics when comes to syntax design. Ruby can get
away with looking a bit messy and haphazard, but that's
not acceptable in the Python community.

There are also semantic problems with the idea in Python.
Once you're allowed to write the code block in-line, it
becomes expected that you can write things like:

   while some_condition:
     with flapple() do (arg):
       if some_other_condition:

and have the 'break' exit from the while-loop. But if
the body is actually a separate function, this is not
easy to arrange.

Back when the existing with-statement was being designed,
there was serious thought put towards implementing it
by passing the body as a function. But handling 'break',
'continue', 'return' and 'yield' inside the body would
have required raising special control-flow exceptions,
and it all got very messy and complicated. In the end
it was decided not to be worth the hassle, and the
existing generator-based implementation was settled on.


More information about the Python-ideas mailing list