Sub topic 12
Making objects iterable
This chapter assumes you can define classes with regular methods and know how for loops and built-in containers like list work. It also assumes you have seen special methods such as __len__ and __getitem__ from the container chapter. Here you will learn the two-method protocol behind every for loop and how to implement it correctly. You will also see the older __getitem__ fallback and the mistakes that cause silent bugs.
Iterables and iterators
Python separates two roles that people often mix up:
- An iterable is an object that can produce an iterator. It defines
__iter__, which returns a new iterator. - An iterator is an object that produces values one at a time. It defines
__next__, which returns the next value or raisesStopIterationwhen there are none left. By convention it also defines__iter__returningself.
A for loop calls iter() once on the object, then calls next() on the result repeatedly until StopIteration is raised.
The loop is equivalent to this code:
def manual_for(iterable, body):
iterator = iter(iterable)
while True:
try:
item = next(iterator)
except StopIteration:
break
body(item)
manual_for([10, 20], print) # 10 then 20A separate iterator class
The clearest design gives the iterable and its iterator different classes. The iterable holds the data. Each call to __iter__ creates a fresh iterator that holds the position.
class Countdown:
def __init__(self, start):
self.start = start
def __iter__(self):
return CountdownIterator(self.start)
class CountdownIterator:
def __init__(self, current):
self.current = current
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
print(list(Countdown(3))) # [3, 2, 1]
c = Countdown(2)
print(list(c), list(c)) # [2, 1] [2, 1]Because Countdown creates a new CountdownIterator on each loop, two loops over c do not interfere. Two nested loops over the same object also work independently.
The one-class shortcut and its cost
You can put both methods on one class by returning self from __iter__:
class OneShotCountdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
c = OneShotCountdown(2)
print(list(c), list(c)) # [2, 1] []The second list(c) is empty because the position lives on the object and nothing resets it. That is correct behavior for an iterator, and file objects and generators behave the same way. It is a bug if you meant the class to be a reusable collection.
| Design | `__iter__` returns | Reusable? | Use for |
|---|---|---|---|
| Separate iterator class | a new iterator | Yes | Collections and views of data |
| Iterator is the iterable | `self` | No, one pass | Streams, files, generators |
Generators: the shortest correct way
In practice, write __iter__ as a generator function. Python builds the iterator class for you, including __next__ and StopIteration. Each call to __iter__ returns a new generator, so the object is reusable.
class Countdown:
def __init__(self, start):
self.start = start
def __iter__(self):
current = self.start
while current > 0:
yield current
current -= 1
c = Countdown(3)
print(list(c), list(c)) # [3, 2, 1] [3, 2, 1]
print(sum(c)) # 6Hand-written __next__ is still worth knowing. Use it when the iterator needs extra methods, when you must expose state, or when you want to see how the protocol works.
The `__getitem__` fallback
If a class has no __iter__ but has __getitem__, iter() builds an iterator that calls obj[0], obj[1], obj[2], and so on. It stops when IndexError is raised. This is why the Playlist class from the container chapter works in a for loop without __iter__.
class Playlist:
def __init__(self, songs):
self._songs = list(songs)
def __len__(self):
return len(self._songs)
def __getitem__(self, index):
return self._songs[index]
p = Playlist(['Intro', 'Verse', 'Outro'])
for song in p:
print(song)
print(list(reversed(p))) # ['Outro', 'Verse', 'Intro']reversed() works here because the class has __len__ and __getitem__. You can also define __reversed__ to return your own reverse iterator.
The fallback has limits:
- It only works for integer indexes starting at 0. A dict-like class that raises
KeyErrorfor a missing key will propagate that error out of the loop. isinstance(p, collections.abc.Iterable)returnsFalseforPlaylist, even thoughiter(p)works. The check looks for__iter__only.- Define
__iter__explicitly when you want a clear, fast, checkable contract.
Who consumes the protocol
Many operations call iter() for you, so one __iter__ makes a class work with all of them:
| Operation | Example |
|---|---|
| Loops and comprehensions | `for x in obj`, `[x for x in obj]` |
| Constructors | `list(obj)`, `set(obj)`, `tuple(obj)` |
| Reductions | `sum(obj)`, `min(obj)`, `max(obj)`, `sorted(obj)` |
| Unpacking | `a, b = obj`, `print(*obj)` |
| Membership | `x in obj` when there is no `__contains__` |
If you define __contains__, in uses it and does not iterate.
Edge cases and common errors
- Forgetting
__iter__on the iterator. Aforloop callsiter()on the iterable, not on the iterator, so this error shows up only when someone passes your iterator to something that callsiter()on it. Always returnselffrom the iterator's__iter__. - Returning a non-iterator from
__iter__.__iter__that returns a list, such asreturn self.items, raisesTypeError: iter() returned non-iterator of type 'list'. Returniter(self.items)instead. - Raising
StopIterationinside a generator. Since Python 3.7, aStopIterationthat escapes a generator body becomesRuntimeError. To end a generator early, usereturn. - Continuing after exhaustion. Once
__next__raisesStopIteration, it should keep raising it on later calls. Do not let it restart. - Mutating while iterating. If your iterator reads live data, changing that data mid-loop can skip or repeat items. Built-in containers raise an error in some cases, and your class will not unless you add a check.
- Blocking iteration. Setting
__iter__ = Nonein a class makesiter()raiseTypeError. Use it when a class defines__getitem__but should not be iterated.
Exercise
What does this print, and why? class Box: with __init__(self, items) storing self.items = items, __iter__(self) returning self.items where items is a list, then for x in Box([1, 2]): print(x).
Show answer
It raises TypeError: iter() returned non-iterator of type 'list'. A list is iterable but is not an iterator, because it has no __next__. Fix it by returning iter(self.items), or by writing __iter__ as a generator with yield from self.items.
Exercise
You write a Stream class whose __iter__ returns self and whose __next__ reads the next line from an open file. A caller runs list(s) and then list(s) again. What does the second call return, and is that a bug?
Show answer
The second call returns []. It is not a bug: Stream is an iterator over a one-pass resource, so it is exhausted after the first pass. If callers need repeated passes, create a separate iterable class whose __iter__ opens the source again and returns a new iterator each time.