Python: Track source reads when itertools.tee consumers diverge
itertools.tee() lets consumers advance independently over one source iterator. It reads the source only as needed and retains values for a consumer that falls behind; it does not run the source separately for each branch.
Tested on Linux with Python 3.12.14. Use Python 3.12 or newer. The example uses only the standard library and requires no network access.
Run the example
Save this as iterator_branches_demo.py in an empty working directory:
from itertools import tee
def readings():
for value in (10, 20, 30):
print("Source read:", value)
yield value
fast, slow = tee(readings())
print("Fast:", next(fast))
print("Fast:", next(fast))
print("Slow:", next(slow))
print("Slow:", next(slow))
print("Slow:", next(slow))
print("Fast:", next(fast))Run it without -O so any assertions remain enabled:
python3 iterator_branches_demo.pyCaptured output:
Source read: 10
Fast: 10
Source read: 20
Fast: 20
Slow: 10
Slow: 20
Source read: 30
Slow: 30
Fast: 30The slow branch receives 10 and 20 without another source read. It then pulls 30 first, and the fast branch later receives that saved value. This trace demonstrates shared consumption, not a measurement of the internal buffer size.
Limits and cleanup
Do not keep advancing the original iterator after splitting it. Large gaps between consumers can require substantial auxiliary storage; a finite materialized list may be clearer if one consumer will finish before the other starts. The returned iterators are not thread-safe.
After testing, remove the example script from its working directory:
rm -- iterator_branches_demo.pyReference
Acknowledgements
This post was created with assistance from AI.