Call to
next()
should be wrapped in try-except
49def load_one(lit: LineIterator) -> dict:
50 """Do not edit this docstring. It will be overwritten."""
51 # check header
52 line = next(lit) 53 if not line.startswith(" &FCI NORB="):
54 raise LoadError(f"Incorrect file header: {line.strip()}", lit)
55
Description
Calls to next()
should be inside try-except
block.
When the iterator is exhausted, StopIteration
exception is raised. When used inside a generator, this can cause unexpected behavior. If not handled, it will propagate out of the generator causing termination. PEP-479 has been accepted to fix this problem. It will modify the behavior of StopIteration
in generators.
Each call to next()
should be wrapped in a try-except
block to explicitly handle StopIteration
exceptions.
Bad practice
def get_team_structure(team):
for team in class:
students = iter(team)
# StopIteration exception will be raised if team doesn't have members.
leader = next(students)
members = [m for m in students]
yield leader, members
def print_teams(teams):
for leader, members in get_team_structure(teams):
print("Leader: "leader)
for member in members:
print(member)
Recommended:
def get_team_structure(team):
for team in class:
# StopIteration exception will be raised if team has no members.
students = iter(team)
# Added `try` block, to guard against the exception
try:
leader = next(students)
except StopIteration:
# team has no members, skip it
continue
members = [m for m in students]
yield leader, members
def print_teams(teams):
for leader, members in get_team_structure(teams):
print("Leader: "leader)
for member in members:
print(member)
...