Add another example of PEP 479 justification, courtesy of Isaac Schwabacher

This commit is contained in:
Chris Angelico 2014-12-07 02:45:03 +11:00
parent d6edada20d
commit a09e8b3dae
1 changed files with 16 additions and 3 deletions

View File

@ -72,9 +72,9 @@ stumble on these cases by accident::
print('commit')
def do_it():
print('Refactored preparations')
print('Refactored initial setup')
yield # Body of with-statement is executed here
print('Refactored finalization')
print('Refactored finalization of successful transaction')
def gene():
for i in range(2):
@ -92,7 +92,20 @@ subtle bug: if the wrapped block raises ``StopIteration``, under the
current behavior this exception will be swallowed by the context
manager; and, worse, the finalization is silently skipped! Similarly
problematic behavior occurs when an ``asyncio`` coroutine raises
``StopIteration``, causing it to terminate silently.
``StopIteration``, causing it to terminate silently, or when ``next``
is used to take the first result from an iterator that unexpectedly
turns out to be empty, for example::
# using the same context manager as above
import pathlib
with transaction():
print('commit file {}'.format(
# I can never remember what the README extension is
next(pathlib.Path('/some/dir').glob('README*'))))
In both cases, the refactoring abstraction of ``yield from`` breaks
in the presence of bugs in client code.
Additionally, the proposal reduces the difference between list
comprehensions and generator expressions, preventing surprises such as