Advertisement
Advanced Python, Iterators & the Iterator Protocol

How does the iterator protocol interact with the with-statement for resource-managing iterables like file objects?

Short answer

A file object is simultaneously a context manager (via __enter__/__exit__) and an iterator (via __iter__/__next__).

Save Python mock interview
Advertisement
AModel answer
A file object is simultaneously a context manager (via __enter__/__exit__) and an iterator (via __iter__/__next__). Using `with open(...) as f: for line in f:` combines both protocols so the file is guaranteed to close via __exit__ even if an exception interrupts the iteration midway through the for-loop.
with open('log.txt') as f:
    for line in f:
        if 'ERROR' in line:
            process(line)
# file automatically closed here, even on exception
Real-world example
A log-tailing tool relies on this pairing to ensure file handles are always released promptly even when processing raises an unexpected exception mid-file.
Likely follow-ups
  • What happens if an exception occurs inside the for-loop body?
  • How would you write a class combining both protocols?
Related topics