Python: Treat iterator length_hint as an estimate
operator.length_hint() can report an estimated iterator length. A consumer must still iterate to discover how many values are actually available. A hint is unsuitable for validating a record count.
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_hint.py in an empty working directory:
from operator import length_hint
class EstimatedRows:
def __init__(self):
self.rows = iter(["row-a", "row-b"])
def __iter__(self):
return self
def __next__(self):
return next(self.rows)
def __length_hint__(self):
return 99
rows = EstimatedRows()
print("Hint:", length_hint(rows))
items = list(rows)
print("Actual count:", len(items))
print("Items:", items)
print("Hint after exhaustion:", length_hint(rows))Run it without -O so any assertions remain enabled:
python3 iterator_hint.pyCaptured output:
Hint: 99
Actual count: 2
Items: ['row-a', 'row-b']
Hint after exhaustion: 99This iterator deliberately returns a loose estimate of 99 while yielding two rows. It keeps returning 99 after exhaustion. The example demonstrates why a hint cannot prove that any items remain.
Limits and cleanup
The function first tries the actual length, then an object’s length hint, and otherwise uses its default. Materializing a small finite iterator gives an exact count but consumes it and stores its values. Do not turn an unbounded or very large stream into a list merely to check a hint.
After testing, remove the example script from its working directory:
rm -- iterator_hint.pyReference
Acknowledgements
This post was created with assistance from AI.