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

Manuel Alejandro Cerón Estrada ceronman at gmail.com
Sat Dec 8 23:13:52 CET 2007


2007/12/8, Raymond Hettinger <python at rcn.com>:
> In your example, why do you "raise StopIteration" instead just writing "return"?

In the example would be better to use 'return' rather than 'raise
StopIteration'. In most cases 'return' will have the same behavior
than 'raise StopIteration', but not always.

Acording to PEP 255:

    Note that return isn't always equivalent to raising StopIteration:  the
    difference lies in how enclosing try/except constructs are treated.

The trivial example is the empty generator where return is ambiguous
with the same statement for normal functions.

Maybe my proposal can change to "Replace 'return' with 'yield break'
in generators"

Again, PEP 255 talks about the possibility of removing 'return' from generators

    Q. Why allow "return" at all?  Why not force termination to be spelled
       "raise StopIteration"?

    A. The mechanics of StopIteration are low-level details, much like the
       mechanics of IndexError in Python 2.1:  the implementation needs to
       do *something* well-defined under the covers, and Python exposes
       these mechanisms for advanced users.  That's not an argument for
       forcing everyone to work at that level, though.  "return" means "I'm
       done" in any kind of function, and that's easy to explain and to use.
       Note that "return" isn't always equivalent to "raise StopIteration"
       in try/except construct, either (see the "Specification: Return"
       section).

Of curse, the problem of low level details it's solved by 'yield break'

Manuel.


More information about the Python-Dev mailing list