Custom containers
Expose a custom collection to for loops and other iterable consumers.
Python · Module
__iter__ is the special method Python calls when it needs an iterator for a container. Implement it to return an iterator over the container’s contents; mappings conventionally iterate over keys.
Define __iter__ on a container when iter(obj) or a for loop should traverse it. The method returns an iterator over the container’s contents; mappings conventionally yield keys, while sequences yield values.
object.__iter__(self)| Name | Type | Description |
|---|---|---|
self | object | The instance whose contents should be exposed through iteration. |
A new iterator object that can iterate over all objects in the container.
class Batch:
def __init__(self, items):
self._items = tuple(items)
def __iter__(self):
return iter(self._items)
for item in Batch(["a", "b"]):
print(item)The class exposes its stored values to for loops by returning a fresh iterator over the tuple.
Expose a custom collection to for loops and other iterable consumers.
Yield values lazily instead of constructing a complete result collection.
Provide standard key iteration for mapping-like objects.
__iter__ is called when an iterator is required for a container. It should return a new iterator that can traverse the container’s objects.
Follow-up: What should a mapping’s __iter__ yield? It should iterate over the mapping’s keys.
A for loop obtains an iterator from the object, then repeatedly requests values from that iterator until iteration ends. A generator function is one way to produce such an iterator because calling it returns an iterator object.
Follow-up: What ends a generator’s iteration? Returning or reaching the end raises StopIteration internally to mark the end of its values.
A class may support iteration through the sequence protocol even without __iter__: iter() can use __getitem__ with integer arguments beginning at zero. If neither protocol is supported, iter() raises TypeError.
Follow-up: How can this fallback be disabled? Set the class’s __iter__ attribute to None; then iter() raises TypeError instead of falling back to __getitem__.
object.__aiter__object.__getitem__iter()iterator.__next__StopIteration