pytest-dev/pytest · error · AttributeError

module not available in {self.scope}-scoped context

Error message

module not available in {self.scope}-scoped context

What it means

Raised by `request.module` when the request scope is not one of "function", "class", or "module". A module object is only resolvable for scopes at-or-narrower than module scope; session and package scoped requests do not map to a single module, so pytest raises AttributeError.

Source

Thrown at src/_pytest/fixtures.py:607

        """Class (can be None) where the test function was collected."""
        if self.scope not in ("class", "function"):
            raise AttributeError(f"cls not available in {self.scope}-scoped context")
        clscol = self._pyfuncitem.getparent(_pytest.python.Class)
        if clscol:
            return clscol.obj

    @property
    def instance(self):
        """Instance (can be None) on which test function was collected."""
        if self.scope != "function":
            return None
        return getattr(self._pyfuncitem, "instance", None)

    @property
    def module(self):
        """Python module object where the test function was collected."""
        if self.scope not in ("function", "class", "module"):
            raise AttributeError(f"module not available in {self.scope}-scoped context")
        mod = self._pyfuncitem.getparent(_pytest.python.Module)
        assert mod is not None
        return mod.obj

    @property
    def path(self) -> Path:
        """Path where the test function was collected."""
        if self.scope not in ("function", "class", "module", "package"):
            raise AttributeError(f"path not available in {self.scope}-scoped context")
        return self._pyfuncitem.path

    @property
    def keywords(self) -> MutableMapping[str, Any]:
        """Keywords/markers dictionary for the underlying node."""
        node: nodes.Node = self.node
        return node.keywords

    @property

View on GitHub (pinned to 98b357f69e)

Solutions

  1. Read the module from the node instead: `request.node.getparent(pytest.Module)` and use `.obj`.
  2. Restrict the fixture to `scope="module"` if it truly needs the module object.
  3. Pass the module identity down from a module-scoped fixture into the session-scoped one via a parameter.

Example fix

// before
@pytest.fixture(scope="session")
def cache(request):
    key = request.module.__name__  # AttributeError
// after
@pytest.fixture(scope="session")
def cache(request):
    mod = request.node.getparent(pytest.Module)
    key = mod.obj.__name__ if mod is not None else "global"
Defensive patterns

Strategy: validation

Validate before calling

if request.scope in ("function", "class", "module"):
    mod = request.module
else:
    mod = request.node.getparent(_pytest.python.Module)

Type guard

def can_access_module(request) -> bool:
    return getattr(request, "scope", None) in ("function", "class", "module")

Try / catch

try:
    mod = request.module
except AttributeError:
    mod = None

Prevention

When it happens

Trigger: Accessing `request.module` inside a fixture declared `scope="session"` or `scope="package"`. e.g. a session-scoped fixture that calls `request.module.__name__` to key a cache.

Common situations: Caching resources per-module from a session-scoped fixture and reaching for `request.module` to build the cache key. Moving a module fixture up to session scope to avoid re-setup.

Related errors


AI-assisted analysis of pytest-dev/pytest@98b357f69e (2026-08-04). Data as JSON: /data/errors/2555766fb0e0a074.json. Report an issue: GitHub.