Audited Lazy File Streaming with Generators, Decorators and with
Data Structure DesignModel answerLast updated
Build a decorator that audits a chunked file-reading generator's lifecycle, with deterministic file cleanup on completion, early exit, errors and garbage collection.
Background
A service that scans very large log dumps must neither load them whole into memory nor leak open file descriptors. Python offers three tools that cover this between them:
- Generators produce values on demand and can be stopped early with
close()orthrow(). - Context managers (
__enter__/__exit__, or thewithstatement) guarantee that cleanup code runs. - Decorators wrap a callable to add behaviour without editing its body.
Task
Write a small, audited streaming reader that uses all three.
1. track_stream(metrics: dict)
A decorator factory for generator functions. The wrapped function must still behave as a lazy generator (never collect results into a list), and it must update the shared metrics dictionary as follows:
metrics['active_streams']goes up by one as soon as the generator object is created, before anynext()call.metrics['active_streams']goes down by one when the stream ends, whether through normal exhaustion, early close by the consumer, or an exception.metrics['total_yields']goes up by one for each item delivered.metrics['exceptions']goes up by one when an unhandled exception ends the stream.GeneratorExit(an ordinary early exit) must not be counted.
2. stream_chunks(file_path: str, chunk_size: int = 1024)
A generator decorated with @track_stream(metrics) that yields successive pieces of the file, each at most chunk_size characters long. The file must be closed promptly however the generator ends: exhaustion, break, close(), an error, or garbage collection.
from typing import Callable, Generator
def track_stream(metrics: dict) -> Callable: ...
def stream_chunks(file_path: str, chunk_size: int = 1024) -> Generator[str, None, None]: ...
Example
metrics = {'active_streams': 0, 'total_yields': 0, 'exceptions': 0}
# 'access.log' holds 2500 characters
g = stream_chunks('access.log', chunk_size=1000)
assert metrics['active_streams'] == 1 # counted before iteration starts
first = next(g)
assert len(first) == 1000
assert metrics['total_yields'] == 1
g.close() # early exit
assert metrics['active_streams'] == 0
Constraints and edge cases
- Never read the whole file into memory at once.
- A consumer
breakmust be handled cleanly and must not be recorded as an exception. - The file must be closed even if an error occurs mid-stream.
- Several consumers may run at the same time, and the counters must stay accurate.
What to deliver
Explain your design, justify how each termination path is handled, state complexity, list the edge cases you considered, and give working code.
Hints
Hint 1
Write the naive version first: a wrapper that is itself a generator function with try/finally. Then check what happens when you create it and call close() without ever calling next(). When does its body first run?
Hint 2
To count at creation time you must return an object immediately, not a generator that has not started. Consider a small class that subclasses collections.abc.Generator, holds the real generator, and forwards send, throw and close to it.
Hint 3
Make the 'finish' step idempotent and protect counter updates with a lock. Put the file inside a with block in the inner generator so every unwinding path (return, exception, GeneratorExit) closes it. Remember that an exception in a consumer's for-loop body is invisible to the generator.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
Two mechanisms split the work:
- Inside the generator: a
with open(...)block wrapped around theyieldloop. Normal exhaustion, an exception, andclose()(which raisesGeneratorExitat the suspendedyield) all unwind through that block, so the file is always closed. - Around the generator: a decorator that returns a small proxy object implementing the generator protocol and doing the bookkeeping.
Why a plain wrapper generator fails
The obvious wrapper is a generator function that increments the counter, then does try: yield from inner finally: decrement. Two problems:
- A generator's body does not execute until the first
next(). The example assertsactive_streams == 1right after construction, so the increment would be too late. - Calling
close()on a generator that never started just marks it finished. Itsfinallynever runs, so the decrement is lost and the counter leaks.
So the wrapper must be an ordinary callable that eagerly builds an object, and that object must decrement exactly once on every termination path, including "closed before it started".
Design of the proxy
_AuditedStream subclasses collections.abc.Generator, which supplies __iter__ and __next__ (via send(None)). It implements:
__init__: stores the inner generator, metrics dict and lock; then incrementsactive_streamsunder the lock. The file is not opened yet, so creating and discarding a stream leaks nothing._finish(failed=False): idempotent. Under the lock, if not already done, mark done, decrementactive_streams, and optionally incrementexceptions. Repeated calls cannot drive counters negative or double-count.send/throw: delegate to the inner generator. On success, incrementtotal_yields. OnStopIterationorGeneratorExit, call_finish()and re-raise. On any other exception, call_finish(failed=True)and re-raise.close(): callinner.close()(a no-op for an unstarted generator), then_finish(). If closing itself raises, count a failure.__del__: callsclose()defensively so an abandoned stream is still accounted for.__enter__/__exit__: lets callers writewith stream_chunks(...) as s:.__exit__records a consumer-side exception (if the stream is still live and the exception is notGeneratorExit), then closes.
Code
import functools
import threading
from collections.abc import Generator as GeneratorABC
class _AuditedStream(GeneratorABC):
def __init__(self, inner, metrics, lock):
self._inner = inner
self._metrics = metrics
self._lock = lock
self._done = False
with lock:
metrics['active_streams'] += 1
def _finish(self, failed=False):
with self._lock:
if self._done:
return
self._done = True
self._metrics['active_streams'] -= 1
if failed:
self._metrics['exceptions'] += 1
def _step(self, op, *args):
try:
item = op(*args)
except (StopIteration, GeneratorExit):
self._finish()
raise
except BaseException:
self._finish(failed=True)
raise
with self._lock:
self._metrics['total_yields'] += 1
return item
def send(self, value):
return self._step(self._inner.send, value)
def throw(self, *args):
return self._step(self._inner.throw, *args)
def close(self):
try:
self._inner.close()
except BaseException:
self._finish(failed=True)
raise
self._finish()
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
if exc_type is not None and not issubclass(exc_type, GeneratorExit):
self._finish(failed=True) # no-op if already finished
self.close()
return False # never swallow the error
def __del__(self):
try:
if not getattr(self, '_done', True):
self.close()
except Exception:
pass
def track_stream(metrics):
lock = threading.Lock()
def decorator(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
return _AuditedStream(fn(*args, **kwargs), metrics, lock)
return wrapper
return decorator
metrics = {'active_streams': 0, 'total_yields': 0, 'exceptions': 0}
@track_stream(metrics)
def stream_chunks(file_path, chunk_size=1024):
if chunk_size <= 0:
raise ValueError("chunk_size must be positive")
with open(file_path, 'r') as f:
while True:
chunk = f.read(chunk_size)
if not chunk:
return
yield chunk
Walk through each termination path
| Path | What happens | Counters |
|---|---|---|
| Exhaustion | inner returns, StopIteration reaches _step | decrement, no exception |
| Generator-side error | with closes file, exception reaches _step | decrement, exceptions += 1 |
close() / early exit | GeneratorExit at the yield, with closes file | decrement, no exception |
Close before first next() | inner close() is a no-op, proxy still finishes | decrement |
| Garbage collection | __del__ calls close(); inner generator's finalizer also closes the file | decrement |
Consumer error in with ... as s: | __exit__ records it, then closes | decrement, exceptions += 1 |
Complexity
- Time: O(N) for N characters read, with O(1) proxy overhead per chunk.
- Space: O(
chunk_size) per live stream. The file is never fully materialised.
Concurrency
d[k] += 1 is a read, add, write sequence and is not atomic across threads, even with the GIL, so every metric update takes a lock. The _done check is inside the same lock, so _finish is safe if two threads race to close. A single generator object is still not safe to drive from several threads (it raises ValueError: generator already executing); give each consumer its own stream.
Edge cases and common mistakes
- Empty file: first
next()raisesStopIteration; 0 yields, clean decrement. - Last partial chunk: 2500 chars with size 1000 gives 1000, 1000, 500.
chunk_size <= 0:read(0)would loop forever andread(-1)reads everything. RaiseValueError; it fires lazily on the firstnext()and is counted as an exception.- Missing file:
FileNotFoundErrorsurfaces on the firstnext()and is counted. - Idempotence: repeated
close()ornext()after finish must not push counters negative. breakin a for loop: CPython does not callclose()onbreak. If the stream is bound to a name, it stays open until the last reference disappears. For deterministic cleanup, usewith stream_chunks(...) as s:orcontextlib.closing.- Consumer exceptions: a generator cannot see an error raised in the loop body. Only the
withinterface (or an explicitthrow()) can report it. - Counting
GeneratorExitas an error: the most common mistake; it is a normal shutdown signal. - Materialising with
list(...)in the wrapper defeats laziness. - Metrics binding: the decorator holds a reference to one dict object. Reassigning the name later (
metrics = {...}) silently breaks auditing, so mutate the same dict in tests.