How would you implement a lazy, chainable iterator pipeline (like filter-then-map) from scratch?
Short answer
You can chain iterators by wrapping one iterator's __next__ around another's, pulling values on demand and applying transformations lazily rather than eagerly.
Advertisement
AModel answer
You can chain iterators by wrapping one iterator's __next__ around another's, pulling values on demand and applying transformations lazily rather than eagerly. Each stage only computes a value when the next stage requests it, keeping memory usage constant regardless of input size.
class MapIter:
def __init__(self, it, fn):
self.it, self.fn = it, fn
def __iter__(self):
return self
def __next__(self):
return self.fn(next(self.it))
pipeline = MapIter(iter([1,2,3]), lambda x: x*10)
print(list(pipeline)) # [10, 20, 30]Real-world example
A log-processing tool chains custom filter and transform iterators over a multi-gigabyte log file so only one line is ever held in memory at a time.
Likely follow-ups
- How do generator expressions achieve the same laziness more concisely?
- What's the performance trade-off of custom iterator classes vs generators?
Related topics