Lazy Iteration and Function Wrapping in Python: Generators and Decorators
System DesignModel answerLast updated
Explain how Python generators suspend and resume execution to stream data lazily, and how decorators wrap functions, including a correct wrapper that preserves metadata.
You are asked to explain two core Python features in a short oral sequence. For each one, expect follow-up questions about the mechanism underneath, not only the definition.
squares_list = [x * x for x in range(10_000_000)]
squares_gen = (x * x for x in range(10_000_000))
@timed
def load_prices(path): ...
Part 1: Generators and lazy evaluation
- What is a generator?
- What advantages does it have over a hand-written iterator class or over a materialized sequence such as a list?
- What exactly does
yielddo? - Why is a generator more memory efficient?
- What is lazy evaluation, and where does it help in practice?
Cover the limitations too: single pass, no length or indexing, and when errors surface.
Part 2: Decorators
- Give an example of a decorator you have used or written.
- What is a decorator really doing under the hood?
Cover what @ is equivalent to, when the decorator code runs versus the wrapped function, how to write a wrapper that forwards arguments and the return value, how to preserve metadata, and how to write a decorator that takes arguments.
Assume the audience is a data-focused team, so examples such as streaming records or timing and retrying calls are welcome.
Hints
Hint 1
A generator function returns an object immediately without running its body. Think about what happens each time `next()` is called and what state is kept between calls.
Hint 2
Compare the memory footprint of holding 10 million results at once with holding one result plus the paused frame. Then think about what you lose: re-iteration, `len()`, indexing.
Hint 3
`@timed` above a function is just syntactic sugar for an assignment that rebinds the name. Ask when that assignment runs, and what the new object needs to do with `*args`, `**kwargs` and the return value.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Generators
What it is. A generator is an iterator produced by a function that contains yield (or by a generator expression). Calling the function does not run the body. It returns a generator object. Each next() call runs the body until the next yield, hands back that value, and suspends with the local variables and instruction pointer preserved. When the body ends, StopIteration is raised.
What yield does. It does two things: it produces a value to the caller and it freezes the frame so execution can resume right after it. This is why a generator can maintain state without a class. (send(), throw() and close() also let the caller push values or exceptions into the paused frame, which is the basis of coroutines.)
Versus a hand-written iterator. A class-based iterator needs __iter__, __next__, explicit state fields and manual StopIteration. A generator satisfies the same protocol in a few lines, and loop state lives in ordinary local variables.
def read_records(path):
with open(path) as f:
for line in f:
yield line.rstrip().split(",")
Memory. squares_list materializes 10 million integers: the list holds 8-byte pointers (about 80 MB) plus the int objects themselves (about 28 bytes each for larger values), so several hundred MB in total. squares_gen stores only the paused frame and the range iterator, a couple of hundred bytes, regardless of N. Memory is O(1) instead of O(N), because each value is produced, consumed and discarded.
Lazy evaluation. Values are computed only when requested. Benefits:
- Constant memory for large or unbounded streams (files, sockets, market data feeds).
- Early exit:
next(x for x in gen if cond(x))stops at the first match without computing the rest. - Composable pipelines:
parse(read_records(p))processes one record at a time end to end.
Limitations and common pitfalls.
- Single pass. Once exhausted, a generator yields nothing. Iterating twice silently gives an empty second pass.
- No
len(), indexing or slicing (useitertools.islice). - Deferred errors. A bug in the body, or a bad input, only raises when that item is requested, which can be far from where the generator was created. Argument validation inside a generator function is also delayed until the first
next(). - Resource lifetime. A file opened inside the generator stays open until it is exhausted or closed; use
withand ensure it is closed. - Not always faster. Laziness saves memory, but per-item overhead can make a list comprehension quicker for small data that fits in memory.
Part 2: Decorators
What it is. A decorator is a callable that takes a function and returns a replacement (usually a wrapper that calls the original). This:
@timed
def load_prices(path): ...
is exactly equivalent to:
def load_prices(path): ...
load_prices = timed(load_prices)
Timing. The decorator itself runs once, at definition time (import time for module-level functions). The wrapper it returns runs on every call.
A correct basic decorator.
import functools, time
def timed(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return func(*args, **kwargs)
finally:
print(f"{func.__name__} took {time.perf_counter() - start:.3f}s")
return wrapper
Key points: accept *args, **kwargs so any signature works; return the wrapped function's result (a frequent bug is forgetting it); use try/finally so timing is reported even on exceptions.
functools.wraps. Without it, load_prices.__name__ becomes "wrapper" and the docstring, annotations and __wrapped__ are lost. That breaks debugging, logging, documentation tools and introspection. wraps copies these attributes and sets __wrapped__.
Decorators with arguments. This needs one more layer: a factory that returns the actual decorator.
def retry(times=3, delay=0.5):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(times):
try:
return func(*args, **kwargs)
except IOError:
if attempt == times - 1:
raise
time.sleep(delay)
return wrapper
return decorator
@retry(times=5)
def fetch_quotes(url): ...
Here @retry(times=5) first calls retry(5) to get decorator, then applies it to the function.
Real examples. functools.lru_cache (memoization), @property, @staticmethod, @classmethod, contextlib.contextmanager (which itself wraps a generator), and in application code: timing, retries, authentication checks, logging, input validation.
Common mistakes.
- Forgetting
functools.wraps. - Not returning the result or dropping keyword arguments.
- Retrying on non-idempotent operations or catching bare
Exception. - Stacking order confusion: with
@aabove@b, the result isa(b(func)), sobwraps first. - Decorating methods and forgetting that
selfarrives through*args.
Tying them together
Both features rely on Python treating functions and frames as first-class objects. In a data pipeline, a generator streams records in constant memory, while decorators add cross-cutting behavior (timing, retries, caching) around each stage without touching the stage's logic.