When you write a
for loop, Python does more work than it looks like. It calls the special method __iter__() on your object to get an iterator. Then it repeatedly calls next(iterator) until that call raises StopIteration. This is how loops actually move through data.Under the hood
# Step through a list by hand
my_list = [10, 20, 30]
iterator = iter(my_list)
print(next(iterator)) # 10
print(next(iterator)) # 20
print(next(iterator)) # 30
try:
# Nothing left: raises StopIteration
print(next(iterator))
except StopIteration:
print('Done')To make your own class work in a
for loop, you define two methods. The collection's __iter__() returns an iterator object. That iterator must have a __next__() method that returns the next value or raises StopIteration when it runs out.A countdown you can loop again
class ReusableCountdown:
def __init__(self, start):
self.start = start
def __iter__(self):
# A fresh iterator for each loop
return CountdownIterator(self.start)
class CountdownIterator:
def __init__(self, current):
self.current = current
def __iter__(self):
# A for loop can use it too
return self
def __next__(self):
if self.current < 1:
raise StopIteration
val = self.current
self.current -= 1
return val
countdown = ReusableCountdown(3)
print(list(countdown)) # [3, 2, 1]
print(list(countdown)) # [3, 2, 1] againWhy separate classes? An iterator is used up after one pass. If
__iter__ returned the same object every time, you couldn't loop over it twice. By creating a new iterator instance inside __iter__, each for loop gets its own independent state.