Interesting talk on Python vs. Ruby and how he would like Python to have just a bit more syntactic flexibility.

Gregory Ewing greg.ewing at canterbury.ac.nz
Fri Feb 19 06:52:20 CET 2010


Steve Howell wrote:

> Python may not support the broadest notion of anonymous functions, but
> it definitely has anonymous blocks.  You can write this in Python:
> 
>     for i in range(10):
>         print i
>         print i * i
>         print i * i * i

There's a clear difference between this and a Ruby block,
however. A "block" in Ruby is implemented by passing a
callable object to a method. There is no callable object
corresponding to the body of a for-loop in Python.

The important thing about Ruby blocks is not that they're
anonymous, but that they're concrete objects that can
be manipulated.

The Ruby approach has the advantage of making it possible
to implement user-defined control structures without
requiring a macro facility. You can't do that in Python.

However, there's something that Python's iterator protocol
makes possible that you can't do with a block-passing
approach. You can have multiple iterators active at once,
and pull values from them as an when required in the
calling code. Ruby's version of the iterator protocol
can't handle that, because once an iterator is started
it retains control until it's finished.

Also, most people who advocate adding some form of
block-passing facility to Python don't seem to have
thought through what would happen if the block contains
any break, continue, return or yield statements.

This issue was looked into in some detail back when there
was consideration of implementing the with-statement
by passing the body as a function. Getting these
statements to behave intuitively inside the body
turned out to be a very thorny problem -- thorny enough
to cause the block-passing idea to be abandoned in
favour of the current implementation.

-- 
Greg



More information about the Python-list mailing list