Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions doc/data/messages/s/stop-iteration-return/bad.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
def fruit_generator():
for fruit in ["apple", "banana"]:
yield fruit
raise StopIteration # [stop-iteration-return]


def two_fruits_generator(fruits):
for fruit in fruits:
yield fruit, next(fruits) # [stop-iteration-return]


def two_good_fruits_generator(fruits):
for fruit in fruits:
if not fruit.is_tasty():
continue
while True:
next_fruit = next(fruits) # [stop-iteration-return]
if next_fruit.is_tasty():
yield fruit, next_fruit
break
3 changes: 2 additions & 1 deletion doc/data/messages/s/stop-iteration-return/details.rst
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
You can help us make the doc better `by contributing <https://github.com/PyCQA/pylint/issues/5953>`_ !
It's possible to give a default value to ``next`` or catch the ``StopIteration``,
or return directly. A ``StopIteration`` cannot be propagated from a generator.
33 changes: 32 additions & 1 deletion doc/data/messages/s/stop-iteration-return/good.py
Original file line number Diff line number Diff line change
@@ -1 +1,32 @@
# This is a placeholder for correct code for this message.
def fruit_generator():
"""The example is simple enough you don't need an explicit return."""
for fruit in ["apple", "banana"]:
yield fruit


def two_fruits_generator(fruits):
"""Catching the StopIteration."""
for fruit in fruits:
try:
yield fruit, next(fruits)
except StopIteration:
print("Sorry there is only one fruit left.")
yield fruit, None


def two_good_fruits_generator(fruits):
"""A return can be used to end the iterator early, but not a StopIteration."""
for fruit in fruits:
if not fruit.is_tasty():
continue
while True:
next_fruit = next(fruits, None)
if next_fruit is None:
print("Sorry there is only one fruit left.")
yield fruit, None
# We reached the end of the 'fruits' generator but raising a
# StopIteration instead of returning would create a RuntimeError
return
if next_fruit.is_tasty():
yield fruit, next_fruit
break
1 change: 1 addition & 0 deletions doc/data/messages/s/stop-iteration-return/related.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- `PEP 479 <https://peps.python.org/pep-0479/>`_