KatInterview

Lazy Iteration and Function Wrapping in Python: Generators and Decorators

System DesignModel answer
MediumModel answerSystem Designpythongeneratorsdecorators

Last 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

  1. What is a generator?
  2. What advantages does it have over a hand-written iterator class or over a materialized sequence such as a list?
  3. What exactly does yield do?
  4. Why is a generator more memory efficient?
  5. 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

  1. Give an example of a decorator you have used or written.
  2. 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.