
On Sun, Nov 28, 2021 at 09:33:17PM -0800, Paul Bryan wrote:
1. Noted: Python's for statement will happily iterate over an object that only implements __next__.
That is not correct.
class C(object): ... def __next__(self): ... return 1 ... for i in C(): ... print(i) ... Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'C' object is not iterable
2. The documentation is pretty clear on what is expected of an iterator: implement __next__ and __iter__.
That goes back to the PEP introducing the iterator protocol in version 2.1. This is not something new.
3. It is perfectly reasonable for __iter__ to return something other than self; the documentation already reflects this.
Right. Your object can return anything it likes from `__iter__`. But then the object isn't an iterator itself, it is an iterable. That is perfectly fine, many wonderful objects that are iterable aren't iterators (e.g. lists, strings, dicts, sets, etc). -- Steve