The two-argument iter form calls a zero-argument function repeatedly until its return value compares equal to a sentinel.
Python iter(callable, sentinel): stop a pull loop at a declared marker
Operation contract
The owned receipt feeder returns two IDs and then an empty string. iter(feed, "") exposes the two IDs without adding the stop marker to output. The feeder is stateful: another traversal after this one cannot replay the records. The example declares a three-call capacity before constructing the iterator, so a missing sentinel fails through the feeder rather than causing an unbounded pull.
Failure and ownership boundary
The sentinel is compared with equality, not object identity. If an empty string is a valid record, this protocol would discard it and require a different marker. No cleanup hook is supplied by iter itself; a file or socket-backed callable still needs an owned close boundary. Python iterators: exhaustion and repeatable collection ownership, Python assignment expressions: capture a checked value once and Python generator send and close: suspension retains state until cleanup cover related choices.
Working program
from collections import deque
pending = deque(["R41", "R42", ""])
reads = 0
def pull_receipt():
global reads
reads += 1
if reads > 3:
raise ValueError("missing stop marker")
return pending.popleft()
print(list(iter(pull_receipt, "")))
print("calls:", reads)
print("remaining:", list(pending))Output
['R41', 'R42']
calls: 3
remaining: []Costs and limits
One call and equality check occur per accepted value plus the sentinel. Output materialization costs O(n) storage. The explicit call bound protects this fixture from a missing marker; iter alone does not.
Common Mistakes
- Choose a sentinel that cannot also be a valid record.
- A callable iterator does not reopen or clean up its data source.
Connected lessons
Python iterators: exhaustion and repeatable collection ownership, Python assignment expressions: capture a checked value once, Python generator send and close: suspension retains state until cleanup.
