The Iterator Protocol: `__iter__` and `__next__`
Any object with an `__iter__()` returning self and a `__next__()` that advances state and raises `StopIteration` 🛑 when finished is a valid iterator.
class CountDown:
def __init__(self, start):
self.cur = start
def __iter__(self):
return self
def __next__(self):
if self.cur <= 0:
raise StopIteration
val = self.cur
self.cur -= 1
return val
for n in CountDown(3):
print(n) # 3, 2, 1 🚀
# 21. The Iterator Protocol: `__iter__` and `__next__` Any object with an `__iter__()` returning self and a `__next__()` that advances state and raises `StopIteration` 🛑 when finished is a valid iterator: ```python class CountDown: def __init__(self, start): self.cur = start def __iter__(self): return self def __next__(self): if self.cur <= 0: raise StopIteration val = self.cur self.cur -= 1 return val for n in CountDown(3): print(n) # 3, 2, 1 🚀 ``` Every single `for` loop in Python under the hood is just calling `iter()` on your collection and hitting `next()` in a `while True:` block until `StopIteration` fires. 🧠 --- ### Question What exception must `__next__()` raise to tell Python's `for` loop to gracefully stop? 🛑 - [ ] a. `StopIteration` (signals the sequence reached the end cleanly) - [ ] b. `IndexError` (assumes an array was over-indexed) - [ ] c. `SystemExit` because stopping a loop should terminate the OS 💀 - [ ] d. `KeyboardInterrupt` pretending the user smashed Ctrl+C 🤦♂️ --- ### Challenge Write an iterator `StepTwo(start, max_val)` that increases by 2 each turn up to `max_val` and raises `StopIteration`. Loop over `StepTwo(0, 4)` and print each number. 🎯 <details> <summary>Solution</summary> ```python class StepTwo: def __init__(self, start, max_val): self.cur = start self.max = max_val def __iter__(self): return self def __next__(self): if self.cur > self.max: raise StopIteration val = self.cur self.cur += 2 return val for n in StepTwo(0, 4): print(n) ``` </details>