What is the difference between __iter__ returning self versus returning a separate iterator object?
Short answer
If a class's __iter__ returns self, the object is both iterable and iterator, meaning it can only be iterated once -- a second for-loop over the same instance starts from wherever the first left off (likely exhausted).
Advertisement
AModel answer
If a class's __iter__ returns self, the object is both iterable and iterator, meaning it can only be iterated once -- a second for-loop over the same instance starts from wherever the first left off (likely exhausted). If __iter__ returns a fresh iterator object each time, the class is a reusable iterable that supports multiple independent iteration passes, which is the more robust and expected design for container-like classes.
class ReusableRange:
def __init__(self, n):
self.n = n
def __iter__(self):
return iter(range(self.n)) # fresh iterator each call
r = ReusableRange(3)
print(list(r), list(r)) # both give [0, 1, 2]Real-world example
A custom Dataset class in a data pipeline returns a new iterator from __iter__ each epoch so training can loop over the same dataset multiple times.
Likely follow-ups
- Why do generator objects only support single-pass iteration?
- How would you make a generator-based class reusable?
Related topics