All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.py.rules.python.S2876.html Maven / Gradle / Ivy

There is a newer version: 4.23.0.17664
Show newest version

This rule raises an issue when the object returned by __iter__ is not a valid iterator.

Why is this an issue?

An iterable object is an object capable of returning its members one at a time. To do so, it must define an __iter__ method that returns an iterator.

The iterator protocol specifies that, in order to be a valid iterator, an object must define a __next__ and an __iter__ method (because iterators are also iterable).

Defining an __iter__ method that returns anything else than an iterator will raise a TypeError as soon as the iteration begins.

Note that generators and generator expressions have both __next__ and __iter__ methods generated automatically.

How to fix it

Make sure that the __iter__ method returns a valid iterator.

Code examples

Noncompliant code example

class MyIterable:
    def __init__(self, values):
        self._values = values

    def __iter__(self):
        return None  # Noncompliant: Not a valid iterator

Compliant solution

class MyIterable:
    def __init__(self, values):
        self._values = values

    def __iter__(self):
        return MyIterator(self._values)

class MyIterator:
    def __init__(self, values):
        self._values = values
        self._index = 0

    def __next__(self):
        if self._index >= len(self._values):
            raise StopIteration()
        value = self._values[self._index]
        self._index += 1
        return value

    def __iter__(self):
        return self

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy