pytest-dev/pytest · error · AttributeError

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

Error message

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

What it means

Raised by `request.cls` when the request scope is neither "class" nor "function". The class that collected the test is only meaningful inside class- or function-scoped requests; session/module/package requests have no associated class, so pytest raises AttributeError. `request.cls` may also legitimately return None for non-class tests.

Source

Thrown at src/_pytest/fixtures.py:591

    @property
    def config(self) -> Config:
        """The pytest config object associated with this request."""
        return self._pyfuncitem.config

    @property
    def function(self):
        """Test function object if the request has a per-function scope."""
        if self.scope != "function":
            raise AttributeError(
                f"function not available in {self.scope}-scoped context"
            )
        return self._pyfuncitem.obj

    @property
    def cls(self):
        """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

View on GitHub (pinned to 98b357f69e)

Solutions

  1. Guard the access with a scope check: `if request.scope in ("class", "function") and request.cls is not None:`.
  2. Split into a function/class-scoped fixture that reads `request.cls` and feeds the wider-scoped fixture.
  3. Use `request.node.getparent(pytest.Class)` to find a class node without the scope restriction.

Example fix

// before
@pytest.fixture(scope="session")
def cfg(request):
    cls = request.cls  # AttributeError
// after
@pytest.fixture(scope="session")
def cfg(request):
    cls = None
    if request.scope in ("class", "function"):
        cls = request.cls
Defensive patterns

Strategy: validation

Validate before calling

if request.scope in ("class", "function"):
    cls = request.cls
else:
    cls = None

Type guard

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

Try / catch

try:
    cls = request.cls
except AttributeError:
    cls = None

Prevention

When it happens

Trigger: Calling `request.cls` inside a fixture with `scope="session"`, `"module"`, or `"package"`. e.g. `@pytest.fixture(scope="module")\ndef cfg(request):\n if request.cls is not None: ...` raises instead of returning None.

Common situations: Widening a class-aware fixture's scope for performance while still branching on `request.cls`. Sharing a fixture across modules via session scope but leaving class introspection in.

Related errors


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