.. _stop-iteration-return:

stop-iteration-return / R1708
=============================

**Message emitted:**

Do not raise StopIteration in generator, use return statement instead

**Description:**

*According to PEP479, the raise of StopIteration to end the loop of a generator may lead to hard to find bugs. This PEP specify that raise StopIteration has to be replaced by a simple return statement*

**Problematic code:**

.. literalinclude:: /data/messages/s/stop-iteration-return/bad.py
   :language: python

**Correct code:**

.. literalinclude:: /data/messages/s/stop-iteration-return/good.py
   :language: python

**Additional details:**

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.

**Related links:**

- `PEP 479 <https://peps.python.org/pep-0479/>`_

Created by the `refactoring <https://github.com/PyCQA/pylint/blob/main/pylint/checkers/refactoring/refactoring_checker.py>`__ checker.