Several places online, including answers in Stack Overflow (such as this, this & this), mention that Python iterators must implement both the __next__
method (which I understand) and the __iter__
method. These places rightfully conclude that all iterators are also iterables. Even PyCharm issues a type warning if a variable which is annotated to be a typing.Iterator
doesn't implement that __iter__
method.
Contrary to those, the official Python tutorial section on iterators only mentions the need for a __next__
method:
The function returns an iterator object that defines the method
__next__()
which accesses elements in the container one at a time
So my question is: do Python iterators formally need to be iterables on their own? I personally don't understand why this should be true, and why we can't fully separate the requirements for an Iterable
and an Iterator
.