pytest-dev/pytest · error · AttributeError

{name}

Error message

{name}

What it means

Raised by MonkeyPatch.delattr as an AttributeError(name) when the attribute does not exist on target and raising=True (the default). pytest surfaces the missing attribute so the teardown bookkeeping is not silently a no-op.

Source

Thrown at src/_pytest/monkeypatch.py:279

        Raises AttributeError it the attribute does not exist, unless
        ``raising`` is set to False.
        """
        __tracebackhide__ = True
        import inspect

        if name is NOTSET:
            if not isinstance(target, str):
                raise TypeError(
                    "use delattr(target, name) or "
                    "delattr(target) with target being a dotted "
                    "import string"
                )
            name, target = derive_importpath(target, raising)

        if not hasattr(target, name):
            if raising:
                raise AttributeError(name)
        else:
            oldval = getattr(target, name, NOTSET)
            # Avoid class descriptors like staticmethod/classmethod.
            if inspect.isclass(target):
                oldval = target.__dict__.get(name, NOTSET)
            self._setattr.append((target, name, oldval))
            delattr(target, name)

    def setitem(self, dic: Mapping[K, V], name: K, value: V) -> None:
        """Set dictionary entry ``name`` to value."""
        self._setitem.append((dic, name, dic.get(name, NOTSET)))
        # Not all Mapping types support indexing, but MutableMapping doesn't support TypedDict
        dic[name] = value  # type: ignore[index]

    def delitem(self, dic: Mapping[K, V], name: K, raising: bool = True) -> None:
        """Delete ``name`` from dict.

        Raises ``KeyError`` if it doesn't exist, unless ``raising`` is set to

View on GitHub (pinned to 98b357f69e)

Solutions

  1. Pass raising=False to tolerate a missing attribute: monkeypatch.delattr(obj, 'attr', raising=False)
  2. Guard with hasattr(obj, 'attr') before calling delattr
  3. Correct the attribute-name typo

Example fix

// before
monkeypatch.delattr(obj, 'atrr')
// after
monkeypatch.delattr(obj, 'attr', raising=False)
Defensive patterns

Strategy: validation

Validate before calling

if hasattr(target, name):
    monkeypatch.delattr(target, name)
else:
    monkeypatch.delattr(target, name, raising=False)

Type guard

def attr_exists(target, name) -> bool:
    return hasattr(target, name)

Try / catch

try:
    monkeypatch.delattr(target, name)
except AttributeError:
    pass  # attribute absent; acceptable in this test

Prevention

When it happens

Trigger: monkeypatch.delattr(obj, 'missing_attr') with the default raising=True; the attribute is absent (e.g. typo, never set, or already deleted).

Common situations: Typos in attribute names, conditional attributes that were never set this run, attributes removed earlier in the test, or asserts on optional features.

Related errors


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