Pytest Fixture Scope: Share Setup, Not State
Choose fixture scope deliberately: widen it for expensive resources, keep it narrow for mutable data, and verify with pytest --fixtures and --durations.
14 Jul 2025, 11:40 UTC

Every test pays the setup tax
Your test suite starts fast. A single test runs in milliseconds. Then the suite grows, and suddenly pytest takes minutes. The culprit is often the default fixture scope: function. Every test that asks for a database connection, a parsed fixture file, or a temporary container gets a brand-new one, complete with setup and teardown. Isolation is excellent; repetition is expensive.
The engineering decision is not whether to share setup, but where to draw the line. Widen a fixture’s scope and you pay the setup cost once. Keep it narrow and every test starts from a clean slate. The trick is sharing the expensive part without sharing mutable state.
What scope controls in pytest
A fixture is a function that pytest runs before a test and, optionally, tears down afterward. You declare it with @pytest.fixture, and tests request it by naming it as a parameter. The scope argument decides how many times pytest creates it during a run:
function(default): fresh fixture for every test.class: one fixture per test class.module: one fixture per test module.package: one fixture per package directory.session: one fixture for the entire pytest invocation.
A yield-style fixture runs code before yield as setup and code after yield as teardown. Teardown runs even if the test fails, and fixtures are torn down in reverse setup order, so a session-scoped resource is closed after all function-scoped resources that depend on it.
Worked example: one engine, one transaction per test
Imagine a suite that hits a database. Creating the engine and schema is slow, but each test should see pristine data. This pattern keeps the engine at session scope and the transaction at function scope:
# conftest.py
import pytest
from sqlalchemy import create_engine
@pytest.fixture(scope="session")
def engine():
engine = create_engine("sqlite:///:memory:")
# create tables once
yield engine
engine.dispose()
@pytest.fixture
def transaction(engine):
connection = engine.connect()
transaction = connection.begin()
yield connection
transaction.rollback()
connection.close()
Here transaction is function-scoped and depends on engine, which is session-scoped. That direction is allowed: a narrower fixture may request a wider one. The reverse—a session fixture requesting a function fixture—raises a scope-mismatch error.
Run the suite from your project root:
pytest -v
In this pattern, engine is created once and transaction is created and rolled back for every test. No special permissions are required beyond those needed to run pytest itself. The risk is that this pattern assumes the database supports transactions; for a non-transactional store, use a per-test snapshot or an explicit reset fixture instead.
The cost of sharing: hidden coupling
Wide scope introduces coupling that function scope hides. If a test mutates session-scoped data and another test reads it, the second test’s result can depend on whether the first ran first. You get order-dependent flakes: a test passes in isolation but fails in the full suite.
Pytest enforces one structural rule to prevent accidental misuse: a fixture cannot depend on a fixture with a narrower scope. You can trigger this on purpose to confirm the rule:
# This raises a scope-mismatch error
@pytest.fixture(scope="session")
def bad_fixture(short_lived):
yield short_lived
@pytest.fixture
def short_lived():
yield "value"
Run pytest --fixtures from the project root to list every available fixture and its declared scope. Use it as a debugging aid when a fixture is not behaving as expected.
Verify before you widen
Do not guess at speed gains. Run pytest --durations=10 before and after changing a fixture’s scope to see which tests actually consume time. To confirm how often a fixture is created, add a temporary print statement in its setup and teardown, then run pytest -v. Remove the print statements before committing.
Check the documentation for your installed version with pytest --version, because fixture behavior and deprecations can shift between major releases.
Default to function, widen deliberately
Start every fixture at function scope. Widen it only when setup is genuinely expensive and the shared resource is safe to reuse. Pair a wide, read-only resource with a narrow, mutable fixture—such as a transaction or temporary directory—so tests stay isolated while the suite stays fast.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.