[Python-Dev] PEP Idea: Syntactic sugar for StopIteration.

Manuel Alejandro Cerón Estrada ceronman at gmail.com
Sat Dec 8 19:49:54 CET 2007

Hello Python developers.

This is my first post on the list. I have been using Python for a
while and I have been thinking about one feature I would like to see
integrated into the language. I thought it could be a good topic for a
PEP, so I decided to join the list and write about it.

First problem: empty generators.

Suppose you have to write an empty generator. You could do something like:

def foo():
    yield 'never'

Or something like:

def foo():
    yield iter([]).next()


def foo():
    raise StopIteration()
    yield "never"

There is an old thread discussing the diferent alternatives:

Of curse this is unpythonic. It violates the principle of: "There
should be one-- and preferably only one --obvious way to do it".
Instead, we have a bunch of inelegant solutions, and no one is the
obvious one.

Second problem: Explicit raise without explicit try-except.

Take a look at this example:

def lines():
    for line in my_file:
        if some_error():
            raise StopIteration()
        yield line
    yield 'end'

for line in lines():

Even when the lines function contains an explicit raise statement,
there is no explicit try-except block. Of curse, the StopIteration
exception is implicitly caught when the generator is called, but this
looks a bit confusing. In my opinion, every explicitly raised
exception should be explicitly caught by a try-except block.

The solution: yield break.

The solution used in C# for these problems is the 'yield break'
statement.  In this way, the empty generator would look like:

def foo():
    yield break

This would be the pythonic way of writing an empty generator.

In the same way, every time you want to stop the generation you should
call 'yield break', for example:

def lines():
    for line in my_file:
        if some_error():
            yield break
        yield line
    yield 'end'

Note that 'yield break' resembles the 'break' statement used in loops,
while 'StopIteration' doesn't. 'yield break' is more orthogonal to the
rest of the language.

I am looking forward to seeing your opinions.

Manuel Cerón.

More information about the Python-Dev mailing list