iter-method-return-iterable (PYI045)#
Derived from the flake8-pyi linter.
What it does#
Checks for __iter__
methods in stubs that return Iterable[T]
instead
of an Iterator[T]
.
Why is this bad?#
__iter__
methods should always should return an Iterator
of some kind,
not an Iterable
.
In Python, an Iterator
is an object that has a __next__
method, which
provides a consistent interface for sequentially processing elements from
a sequence or other iterable object. Meanwhile, an Iterable
is an object
with an __iter__
method, which itself returns an Iterator
.
Every Iterator
is an Iterable
, but not every Iterable
is an Iterator
.
By returning an Iterable
from __iter__
, you may end up returning an
object that doesn't implement __next__
, which will cause a TypeError
at runtime. For example, returning a list
from __iter__
will cause
a TypeError
when you call __next__
on it, as a list
is an Iterable
,
but not an Iterator
.
Example#
Use instead: