pytest-dev/pytest · error · TypeError

must be absolute import path string, not {import_path!r}

Error message

must be absolute import path string, not {import_path!r}

What it means

`derive_importpath` requires a non-empty `str` containing at least one `.` separating the module path from the attribute. Anything else (non-string, or a string with no dot) raises TypeError. This validates the dotted-string form of `monkeypatch.setattr`/`delattr`.

Source

Thrown at src/_pytest/monkeypatch.py:105

            else:
                raise ImportError(f"import error in {used}: {ex}") from ex
        found = annotated_getattr(found, part, used)
    return found


def annotated_getattr(obj: object, name: str, ann: str) -> object:
    try:
        obj = getattr(obj, name)
    except AttributeError as e:
        raise AttributeError(
            f"{type(obj).__name__!r} object at {ann} has no attribute {name!r}"
        ) from e
    return obj


def derive_importpath(import_path: str, raising: bool) -> tuple[str, object]:
    if not isinstance(import_path, str) or "." not in import_path:
        raise TypeError(f"must be absolute import path string, not {import_path!r}")
    module, attr = import_path.rsplit(".", 1)
    target = resolve(module)
    if raising:
        annotated_getattr(target, attr, ann=module)
    return attr, target


@final
class MonkeyPatch:
    """Helper to conveniently monkeypatch attributes/items/environment
    variables/syspath.

    Returned by the :fixture:`monkeypatch` fixture.

    .. versionchanged:: 6.2
        Can now also be used directly as `pytest.MonkeyPatch()`, for when
        the fixture is not available. In this case, use
        :meth:`with MonkeyPatch.context() as mp: <context>` or remember to call

View on GitHub (pinned to 98b357f69e)

Solutions

  1. Use the dotted form `'module.attr'` for the two-argument `setattr(target_string, value)` call.
  2. Or switch to the three-argument form `setattr(module_obj, 'attr', value)` passing the module object directly.

Example fix

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

Strategy: type-guard

Validate before calling

def is_dotted_string(p) -> bool:
    return isinstance(p, str) and '.' in p

Type guard

def is_dotted_import_path(p: object) -> bool:
    return isinstance(p, str) and '.' in p

Prevention

When it happens

Trigger: `monkeypatch.setattr('os', fake)` (no attribute segment), `monkeypatch.setattr(123, fake)` (non-string), or `monkeypatch.setattr('', fake)`.

Common situations: Passing a module object instead of a dotted string to the two-argument form; forgetting the attribute part of the path.

Related errors


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