Pytest Fixture Scope Selection: Isolation vs. Performance
Default to function-scoped pytest fixtures; session scope saves setup time but its teardown runs once at suite end, which can leak state between tests.
02 Sept 2025, 12:32 UTC

The Problem: Fixture Setup Frequency and Shared State
The problem is deciding how often pytest should run fixture setup and teardown. A session-scoped fixture can reduce the cost of opening database connections or compiling templates, but its teardown runs once when the entire test session ends, not after each test. If one test mutates that shared resource, later tests can observe the change and fail for reasons unrelated to their own logic. The useful takeaway is to use function scope as the default and widen scope only for expensive, read-only resources after profiling shows a real bottleneck.
A fixture is a function marked with @pytest.fixture that supplies data or resources to a test. Scope determines when the code before yield runs (setup) and when the code after yield runs (teardown).
Fixture Scope Levels
| Scope | Setup runs | Teardown runs |
|---|---|---|
function | Before each test that requests the fixture | After that test finishes |
class | Before the first test in the class | After the last test in the class |
module | Before the first test in the file | After the last test in the file |
session | Before the first test in the run | After the last test in the run |
Fixture dependencies are resolved when a test requests them, not before all test code in the session begins. A test that does not request a session-scoped fixture will not trigger its setup.
Smallest Suitable Design
Start with function scope. It gives each test its own fixture instance and teardown, which limits the blast radius of a failure to a single test.
Use session scope only when setup is genuinely expensive and the resource is read-only for the duration of the session:
import pytest
@pytest.fixture(scope="session")
def read_only_connection():
connection = open_expensive_read_only_connection()
yield connection
connection.close() # Runs once at session end
If a session-scoped resource must be modified during a test, do not rely on the session fixture's teardown to undo the change; it runs too late. Add a function-scoped wrapper or reset the state inside each test that modifies it.
Trust and Data Boundaries
Function scope isolates the fixture object itself, but it does not isolate the entire test environment. The following can still leak between tests regardless of fixture scope:
- Global variables and module-level singletons
- Environment variables
- External services, databases, and shared files
- Cached imports or monkeypatched attributes
Treat fixture scope as one layer of isolation, not a guarantee that tests are independent.
Operational Verification
Run from the project directory:
cd /path/to/project
pytest -s tests/test_fixture_scope.py
The -s flag disables stdout capture, which is required to see print output from fixture setup and teardown. Required permissions are ordinary file-read access; pytest must be installed in the active environment.
Expected check: with scope="function", a setup message appears once per test invocation. With scope="session", it appears once for the whole run. If tests are parametrized with @pytest.mark.parametrize, the fixture runs once per parameter set, so the line count will not equal the number of test functions.
Risk: relying on printed output is informal. For a stricter check, have the fixture append an identifier to a list and assert the list length after the run, but remember that the list itself is shared state and must not affect other tests.
Failure Modes and Design Adjustments
Session teardown timing
A session-scoped fixture's teardown executes once at the end of the session. It cannot reset state after every individual test. A test that writes to a shared session resource leaves that write visible to subsequent tests.
Masked failures
Test A modifies a shared database row. Test B assumes the row is in its default state and fails, even though Test B's logic is correct. The failure appears in Test B, making the root cause harder to diagnose.
Adjustment
When sharing is unavoidable, add explicit cleanup inside each test or use a function-scoped fixture that resets the shared resource per test:
import pytest
@pytest.fixture
def isolated_counter(shared_counter):
shared_counter["value"] = 0
yield shared_counter
Conditions That Would Change the Design
- Profiling shows fixture setup dominates test runtime and the resource is read-only.
- External API rate limits require reusing a single authenticated client, accepting that tests are no longer fully isolated.
- The suite runs under pytest-xdist or parallel workers, where session-scoped state is shared across processes in ways that depend on the plugin and configuration.
Limitations
This note covers built-in pytest fixture scopes. It does not address conftest.py inheritance, autouse fixtures, fixture finalization order across plugins, or parallel execution. No minimum pytest version is asserted; function, class, module, and session scopes predate recent releases.
Practical check: change one fixture from function to session, run the affected test file with pytest -v, and confirm tests pass in isolation and in full-suite order. If they pass alone but fail together, shared state is the likely cause.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.