Add more words to GeneratorReturn alternative.

This commit is contained in:
Guido van Rossum 2014-11-17 12:15:42 -08:00
parent 59eb504acb
commit 4e41b5e146
1 changed files with 21 additions and 6 deletions

View File

@ -129,8 +129,18 @@ Making return-triggered StopIterations obvious
For certain situations, a simpler and fully backward-compatible
solution may be sufficient: when a generator returns, instead of
raising ``StopIteration``, it raises a specific subclass of
``StopIteration`` which can then be detected. If it is not that
subclass, it is an escaping exception rather than a return statement.
``StopIteration`` (``GeneratorReturn``) which can then be detected.
If it is not that subclass, it is an escaping exception rather than a
return statement.
The inspiration for this alternative proposal was Nick's observation
[7]_ that if an ``asyncio`` coroutine [8]_ accidentally raises
``StopIteration``, it currently terminates silently, which may present
a hard-to-debug mystery to the developer. The main proposal turns
such accidents in clearly distinguishable ``RuntimeError`` exceptions,
but if that is rejected, this alternate proposal would enable
``asyncio`` to distinguish between a ``return`` statement and an
accidentally-raised ``StopIteration`` exception.
Of the three outcomes listed above:
@ -144,10 +154,10 @@ the original ``GeneratorReturn``, and would reference the original
exception in its ``__cause__``. If uncaught, this would clearly show
the chaining of exceptions.
This alternative does *not* affect the discrepancy between generator expressions
and list comprehensions, but allows generator-aware code (such as the
contextlib and asyncio modules) to reliably differentiate between the
second and third outcomes listed above.
This alternative does *not* affect the discrepancy between generator
expressions and list comprehensions, but allows generator-aware code
(such as the ``contextlib`` and ``asyncio`` modules) to reliably
differentiate between the second and third outcomes listed above.
However, once code exists that depends on this distinction between
``GeneratorReturn`` and ``StopIteration``, a generator that invokes
@ -186,6 +196,11 @@ References
.. [6] wrap unbounded generator to restrict its output
(http://code.activestate.com/recipes/66427-wrap-unbounded-generator-to-restrict-its-output/)
.. [7] Post from Nick Coghlan mentioning asyncio
(https://mail.python.org/pipermail/python-ideas/2014-November/029961.html)
.. [8] Coroutines in asyncio
(https://docs.python.org/3/library/asyncio-task.html#coroutines)
Copyright
=========