More complicated iteration patterns will need explicit try/except constructs. For example, a hypothetical parser like this:
def parser(f):
while True:
data = next(f)
while True:
line = next(f)
if line == "- end -": break
data += line
yield data
would need to be rewritten as:
def parser(f):
while True:
try:
data = next(f)
while True:
line = next(f)
if line == "- end -": break
data += line
yield data
except StopIteration:
return
According to PEP 479 documentation (https://www.python.org/dev/peps/pep-0479/#examples-of-breakage), when
StopIteration
occurs, the generator should end with areturn
statement instead of araise
.See the following example from PEP 479: