Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 38 ยท Fixtures

Fixture Scopes

Learn how fixture scope controls how often setup runs: function, class, module, package and session, with --setup-show examples, scope rules and dynamic scope.

By default a fixture runs again for every test. That is safe, but sometimes wasteful. Opening a database connection, starting a test server, or loading a large file might take seconds, and doing it for each of 500 tests would make the suite crawl. A fixture's scope says how long its value lives before pytest throws it away and builds a fresh one.

Wider scope means faster tests and a higher risk of tests affecting each other. Choosing the right scope is a trade-off, and this lesson gives you the tools to make it.

The five scopes

Scope Setup runs once per... Typical use
function (default) test function any mutable data
class test class a group sharing one resource
module test file a file-level resource
package package (folder with __init__.py) rarely used
session whole pytest run expensive read-only resources: DB connection, compiled data

Set it with @pytest.fixture(scope="...").

Watching scopes with --setup-show

The --setup-show option marks each fixture with a letter: F function, C class, M module, P package, S session. Run this and watch which fixtures are set up once and which are repeated:

Python function, module and session scopes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In the output, config (SETUP S) and database (SETUP M) appear once, while user (SETUP F) appears before each test. Teardown happens in the reverse order when the scope ends.

Shared state: the danger of wide scopes

When a fixture is cached, every test receives the same object. If a test changes it, later tests see the change. Look at what happens here:

Python Wide scope leaks changes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The second test fails purely because of what the first test did, and it would pass if run alone. These order-dependent failures are among the most annoying bugs in a suite. Rules of thumb:

  • Use wide scopes only for objects that are immutable or read-only in the tests (configuration, a compiled regex, a loaded lookup table).
  • If a test must change something shared, restore it afterwards, or give those tests a narrower scope.
  • Add a narrow-scope fixture on top of a wide one to create fresh isolated state from shared infrastructure (for example, one connection per session and one transaction per test).

The scope hierarchy rule

A fixture can only depend on fixtures of the same or a wider scope. A session fixture cannot use a function fixture, because the function fixture would be gone before the session ends. pytest reports a ScopeMismatch error:

Python ScopeMismatch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The reverse is fine: a function fixture may depend on session fixtures, as in the first example.

flowchart TD
    S["session<br/>1 setup per run"] --> P["package"]
    P --> M["module<br/>1 per file"]
    M --> C["class<br/>1 per class"]
    C --> F["function<br/>1 per test"]

A fixture may use anything above it in this chart, never below. Wider scopes live longer.

Class scope

scope="class" shares a fixture across all tests in one class. Tests outside the class get a different instance:

Python Class scope

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Dynamic scope

Sometimes the right scope depends on how pytest is run, for example "session in CI, function locally". Pass a function to scope that receives the fixture name and the config and returns the scope name:

Python
def determine_scope(fixture_name, config):
    if config.getoption("--keep-containers", None):
        return "session"
    return "function"

@pytest.fixture(scope=determine_scope)
def container():
    ...

This is advanced and rare; know it exists.

Choosing a scope

  1. Start with the default (function). Correctness first.
  2. If a fixture is slow and tests do not modify it, widen the scope.
  3. Prefer module or session only when you measured the time saved.
  4. For databases, share the connection at session scope but reset data per test.

Scope and the order of setup

Within one test, pytest sets up fixtures from the widest scope to the narrowest, regardless of the order of parameters, then runs narrower ones. That is why a session fixture is available when a function fixture runs. Within the same scope, the order follows the dependency graph and then the order of parameters. --setup-show always shows the real order.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does scope="session" mean?

    A session-scoped fixture is created the first time a test needs it and torn down at the end of the run.
  2. 2. Which letter does --setup-show use for module-scoped fixtures?

    F is function, C class, M module, P package and S session.
  3. 3. Why does a session-scoped fixture that requests a function-scoped fixture fail?

    A fixture may only depend on fixtures with the same or a wider scope.
  4. 4. When is it safe to use a wide-scoped fixture?

    Shared mutable state creates order-dependent failures. Use wide scopes for read-only resources.

Summary

  • Scope controls how often a fixture is built: function, class, module, package or session.
  • Wider scope speeds up tests but shares one object between them.
  • Use wide scopes only for read-only or carefully reset resources.
  • A fixture can depend only on fixtures with the same or a wider scope.
  • --setup-show reveals scopes and order; dynamic scope can be chosen with a function.

Next: Yield Fixtures and Cleanup