pytest-dev/pytest · error · AttributeError
{name}
Error message
{name} What it means
Raised by MonkeyPatch.delattr when raising=True (the default) and the target does not have the named attribute. This surfaces at line 279 after the hasattr check fails, so the deletion is aborted and the original AttributeError(name) propagates. The error mirrors Python's native delattr behavior but is gated by the raising flag, letting callers opt out for optional attributes.
Solutions
- Verify the attribute exists at test time: hasattr(target, name) before calling delattr, or fix the attribute name.
- Pass raising=False if the attribute is optional: monkeypatch.delattr(target, name, raising=False).
- Align the test with the current API surface of the target module.
Example fix
// before monkeypatch.delattr(settings, 'DEBUG_FLAG') // after monkeypatch.delattr(settings, 'DEBUG_FLAG', raising=False)
Defensive patterns
Strategy: validation
Validate before calling
if raising and not hasattr(target, name):
# attribute absent; decide whether to skip deletion
monkeypatch.delattr(target, name, raising=False) Type guard
def _attr_safe(target, name) -> bool:
return hasattr(target, name) Try / catch
try:
monkeypatch.delattr(target, name)
except AttributeError:
# attribute was absent; acceptable in this test
pass Prevention
- Use raising=False for attributes that may be absent.
- Check hasattr before deleting when the API surface is uncertain.
When it happens
Trigger: monkeypatch.delattr(target, 'nonexistent') with raising left at True; deleting an attribute that was never defined or already removed; typos in attribute names; deleting attributes conditionally mocked away.
Common situations: Test setup assumes a module exposes an attribute that the installed version does not; another fixture already deleted/restored the attribute; refactoring production code renamed or removed the attribute but tests still reference the old name.
Related errors
- use delattr(target, name) or delattr(target) with target…
- use setattr(target, name, value) or setattr(target, value)…
- expected string as 'msg' parameter, got ' '…
- object (type: ) must be callable
- import error in
AI-assisted analysis of pytest-dev/pytest@0d6fbdeffa (2026-08-11).
Data as JSON: /api/errors/2d9147faea9bf3b3.
Report an issue: GitHub.
Appendix: 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 toView on GitHub (pinned to 0d6fbdeffa)