pytest-dev/pytest · error · TypeError

use setattr(target, name, value) with name being a string or

Error message

use setattr(target, name, value) with name being a string or setattr(target, value) with target being a dotted import string

What it means

When the three-argument form of `monkeypatch.setattr` is used (`value` is provided), `name` must be a `str`. If it is not (e.g. an int, the value itself, or NOTSET misuse), TypeError is raised pointing to the correct call signatures.

Source

Thrown at src/_pytest/monkeypatch.py:234

        See the section :ref:`Where to patch <python:where-to-patch>` in the :mod:`unittest.mock`
        docs for a complete explanation, which is meant for :func:`unittest.mock.patch` but
        applies to ``monkeypatch.setattr`` as well.
        """
        __tracebackhide__ = True
        import inspect

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

        oldval = getattr(target, name, NOTSET)
        if raising and oldval is NOTSET:
            raise AttributeError(f"{target!r} has no attribute {name!r}")

        # avoid class descriptors like staticmethod/classmethod
        if inspect.isclass(target):
            oldval = target.__dict__.get(name, NOTSET)
        setattr(target, name, value)
        self._setattr.append((target, name, oldval))

    def delattr(
        self,
        target: object | str,

View on GitHub (pinned to 98b357f69e)

Solutions

  1. Ensure the second positional arg is the string attribute name and the third is the value.
  2. When the name is dynamic, coerce it with `str(name)` before calling.

Example fix

# before
monkeypatch.setattr(os, fake, 'getcwd')
# after
monkeypatch.setattr(os, 'getcwd', fake)
Defensive patterns

Strategy: type-guard

Validate before calling

def valid_setattr_name(name) -> bool:
    return isinstance(name, str)

Type guard

def is_setattr_name(name: object) -> bool:
    return isinstance(name, str)

Prevention

When it happens

Trigger: `monkeypatch.setattr(os, 123, fake)`, or accidentally swapping `name` and `value` like `setattr(os, fake, 'getcwd')`.

Common situations: Swapping the second and third argument; passing a non-string attribute name from dynamic code.

Related errors


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