In Python 3 documentation, the iterator protocol is defined as follows:
The iterator objects themselves are required to support the following two methods, which together form the iterator protocol:
iterator.__iter__()
Return the iterator object itself. This is required to allow both containers and iterators to be used with the for and in statements. This method corresponds to the tp_iter slot of the type structure for Python objects in the Python/C API.
iterator.__next__()
Return the next item from the container. If there are no further items, raise the StopIteration exception. This method corresponds to the tp_iternext slot of the type structure for Python objects in the Python/C API.
I experimented with implementing it through individual object attributes:
class Empty: pass
o = Empty()
o.__iter__ = lambda: o
o.__next__ = lambda: 42
for i in o: print(i)
and got a TypeError
:
TypeError: 'Empty' object is not iterable
What is wrong? Are there any precise rules somewhere about what objects can be used as iterable in for
loop?