Generators solve almost every case. But sometimes you want your own objects to be iterable with for. For that you have to implement two special methods.
The iteration protocol
| Method | What it must do |
|---|---|
__iter__(self) | Return the iterator (normally self) |
__next__(self) | Return the next value, or raise StopIteration when there are no more |
Any class that implements them works with for, list(), sum(), print(*obj)… That is how range, files and generators work internally.
A range of our own
class MyRange:
def __init__(self, start, end, step):
self.end = end
self.step = step
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current >= self.end:
raise StopIteration
value = self.current
self.current += self.step
return value
for n in MyRange(0, 10, 3):
print(n)
# 0
# 3
# 6
# 9
print(list(MyRange(1, 6, 2))) # [1, 3, 5]
Notice that __next__ stores the state in attributes (self.current), whereas a generator stores it automatically in its local variables. Practice with Custom range.
The same idea as a generator
The equivalent generator is much shorter, which is why it is usually preferred:
def my_range(start, end, step):
current = start
while current < end:
yield current
current += step
print(list(my_range(1, 6, 2))) # [1, 3, 5]
An iterable that creates a new iterator each time
With __iter__ returning self, the object is both iterable and iterator, so it runs out. To be able to traverse it several times, make __iter__ a generator:
class Team:
def __init__(self, *names):
self.names = list(names)
def __iter__(self):
for name in self.names:
yield name
team = Team("Ana", "Luis", "Eva")
print(list(team)) # ['Ana', 'Luis', 'Eva']
print(list(team)) # ['Ana', 'Luis', 'Eva'] (it can be repeated)
print(len(list(team))) # 3
Each for calls __iter__, which returns a new generator. This is the most convenient way of making a class iterable.
Common mistakes
- Forgetting to raise
StopIterationin__next__: theforwould never finish. - Forgetting
__iter__: Python saysTypeError: object is not iterable. - Not returning a value in
__next__: the loop would receiveNone. - Reusing an exhausted iterator: create a new one or make
__iter__return a generator. - Modifying a list while looping over it with a
for: it may skip elements. Loop over a copy (for x in items[:]) or build a new list.
Lesson summary
- An iterable can be looped over; an iterator produces the values one at a time and runs out.
- A function with
yieldis a generator: it pauses and resumes, keeping its state. yield fromyields all the elements of another iterable.- Generators can be infinite; use
isliceto take only some. - Generator expressions
(x for x in ...)save memory. - They can be chained into pipelines.
- A class is iterable if it implements
__iter__and__next__.