pytest Fixtures, Decorators, and Generators: Core Python Mechanics
System DesignModel answerLast updated
Three-part fundamentals question on how pytest fixtures are scoped and torn down, how decorators wrap functions, and how generators stream data lazily.
Answer all three parts below. Where a short code snippet makes your explanation more precise, include one — working examples are preferred over abstract descriptions.
Part 1 — pytest Fixtures
Explain what a pytest fixture is and how a test function receives one. Cover the following:
- How pytest discovers a fixture and passes its return value into a test, including the case where one fixture depends on another
- The four available scopes (
function,class,module,session), the speed-versus-isolation trade-off each one represents, and the rule that governs mixing scopes of different lifetimes - How a fixture performs teardown, what mechanism controls whether teardown runs when a test fails, and when teardown is skipped entirely
- How fixtures are made available to tests in multiple files without importing them explicitly
Part 2 — Decorators
Explain what a Python decorator is and what the @some_decorator line above a function definition actually does at runtime. Then write a decorator called timed that:
- Records how long the decorated function takes to run
- Prints or logs the elapsed time whether the call succeeds or raises an exception
- Forwards all positional and keyword arguments to the original function and returns its result unchanged
- Preserves the original function's
__name__and__doc__
Also briefly explain how you would modify timed so it accepts its own configuration argument, for example @timed(unit="ms").
Part 3 — Generators
Explain what a Python generator is and how it differs from a regular function that builds and returns a list. Cover:
- What
yielddoes to a function's execution — how it suspends, what gets preserved, and how the caller resumes it - The iterator protocol a generator object implements
- At least two scenarios where a generator is clearly preferable to a list, and one scenario where a list is the better choice
Then write a generator function matching_lines(path, substring) that opens a log file, yields only the lines that contain substring, and ensures the file is closed correctly even if the caller stops iterating early or an exception occurs. Do not read the entire file into memory at once.
Hints
Hint 1
For Part 1, remember that a fixture's scope must be equal to or broader than the scope of any fixture it depends on — pytest will raise an error otherwise. Think about what conftest.py files are for.
Hint 2
For Part 2, applying @functools.wraps(func) inside your wrapper is what copies __name__, __doc__, and other metadata. To support decorator arguments, you need an extra layer of nesting — a function that returns the actual decorator.
Hint 3
For Part 3, a generator function paired with a try/finally block (or a with statement) is the cleanest way to guarantee the file closes even when the caller breaks out of iteration early — consider what happens to an open file handle if the generator is abandoned mid-way.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Part 1 — pytest Fixtures
A fixture is a function decorated with @pytest.fixture that provides a test with some resource — a database connection, a temp directory, a configured object. When pytest collects a test, it inspects the test's parameter names, finds matching fixture functions by name, calls them, and injects the return values. This is plain dependency injection; there is no import required by the test.
Fixture-on-fixture dependencies work the same way: if fixture b names fixture a as a parameter, pytest resolves the full dependency graph before running any test.
import pytest
@pytest.fixture
def base_url():
return "http://localhost:8080"
@pytest.fixture
def api_client(base_url): # depends on base_url
return {"host": base_url}
def test_health(api_client):
assert "host" in api_client
Scopes control how often a fixture is created and destroyed:
| Scope | Lifetime | Good for |
|---|---|---|
function (default) | One test | Mutable state that must not leak |
class | One test class | Shared setup within a class |
module | One .py file | Expensive but read-only objects |
session | Entire test run | DB connections, browser instances |
Broader scope = faster (fewer setups), narrower scope = safer (better isolation). The constraint: a fixture cannot depend on a fixture with a narrower scope — a session-scoped fixture cannot request a function-scoped one.
Teardown is written as a yield fixture. Everything before yield is setup; everything after is teardown.
@pytest.fixture
def temp_db():
db = create_test_db()
yield db # value given to the test
db.drop() # always runs, even if the test fails
Using yield means teardown runs whether the test passes or fails. The only time teardown is skipped is if the setup itself raises — in that case yield was never reached, so the after-yield block cannot run. Using addfinalizer instead of yield can give finer control in that scenario.
Sharing across files is done by placing fixtures in a conftest.py file. pytest loads any conftest.py it finds on the path from the root to the test file; fixtures defined there are automatically visible to all tests in that directory tree without any import.
Part 2 — Decorators
@timed above a def is syntactic sugar for func = timed(func) — it runs at definition time, not at call time. The decorator receives the original function, wraps it, and returns the wrapper, which then replaces the original name in the module's namespace.
import functools
import time
import logging
log = logging.getLogger(__name__)
def timed(func):
@functools.wraps(func) # copies __name__, __doc__, __module__, etc.
def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
result = func(*args, **kwargs)
return result
except Exception:
raise # re-raise without swallowing
finally:
elapsed = time.perf_counter() - start
log.debug("%s finished in %.4fs", func.__name__, elapsed)
return wrapper
@timed
def fetch_data(url: str) -> dict:
"""Download and parse a JSON resource."""
...
functools.wraps is essential. Without it, fetch_data.__name__ would be "wrapper", which breaks logging, stack traces, and pytest's own introspection.
Decorator with arguments requires one more layer: a factory that returns the decorator.
def timed(unit="s"): # outermost: accepts config
def decorator(func): # middle: receives the function
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return func(*args, **kwargs)
finally:
elapsed = time.perf_counter() - start
scale = 1000 if unit == "ms" else 1
log.debug("%s: %.2f%s", func.__name__, elapsed * scale, unit)
return wrapper
return decorator
@timed(unit="ms")
def process(data): ...
A common mistake is writing a parameterised decorator and forgetting the extra layer, then wondering why @timed(unit="ms") passes a string as func.
Part 3 — Generators
A generator function contains at least one yield. When called, it returns a generator object immediately — no code in the function body runs yet. Iteration drives execution: each call to next() resumes the function from where it last yielded, runs until the next yield, and suspends again. Local variables and the instruction pointer are preserved across suspensions. When the function returns (or falls off the end), StopIteration is raised, signalling the for loop to stop.
A generator implements the iterator protocol — it has both __iter__ (returns itself) and __next__ — so it works anywhere an iterable is expected.
When generators win over lists:
- The dataset is too large to fit in memory (log files, network streams).
- You only need the first N results — no point computing the rest.
- You are building a pipeline of transformations; each stage can be a generator and data flows one item at a time.
When a list is better:
- You need random access by index.
- You need to iterate the data more than once (a generator is single-pass).
- The full result must be serialised or passed to an API that expects a sequence.
Streaming file reader with guaranteed cleanup:
def matching_lines(path: str, substring: str):
"""Yield lines from *path* that contain *substring*.
The file is closed even if the caller abandons iteration early.
"""
with open(path, "r", encoding="utf-8") as fh:
for line in fh: # fh is itself a lazy line iterator
if substring in line:
yield line.rstrip("\n")
# 'with' block closes fh when the generator is exhausted *or*
# when the generator object is garbage-collected / .close() is called,
# because Python sends GeneratorExit into the generator, which
# unwinds the 'with' block normally.
A subtle point: if the caller does break or simply discards the generator, Python eventually calls .close() on it, which throws GeneratorExit at the suspension point. Because the yield is inside the with block, the context manager's __exit__ runs and the file is closed. A bare open() / finally works too, but with is idiomatic and less error-prone.
Connection to pytest: a yield fixture is literally a generator — pytest calls next() to get the setup value, runs the test, then calls next() again (or .close()) to trigger teardown. The three features in this question aren't independent: fixtures are decorated generator functions, which is why understanding all three together gives a cleaner mental model of how pytest works under the hood.