pytest-dev/pytest · error · ImportPathMismatchError
( , , )
Error message
({module_name}, {module_file}, {path}) What it means
Raised by import_path (prepend/append modes) when the imported module's __file__ is None (lines 648-650). After importlib.import_module succeeds, the helper checks mod.__file__; a None file (typical of namespace packages or built-in modules) cannot be matched against the collected path, so ImportPathMismatchError is raised to avoid silently testing the wrong code.
Solutions
- Switch to importlib import mode: --import-mode=importlib.
- Add __init__.py to make the package a regular package with a real __file__.
- Rename the colliding module to avoid shadowing a namespace/builtin.
Example fix
// before pytest --import-mode=prepend // after pytest --import-mode=importlib
Defensive patterns
Strategy: fallback
Validate before calling
import importlib
mod = importlib.import_module(module_name)
if getattr(mod, '__file__', None) is None:
# will mismatch; choose importlib mode or add __init__.py Type guard
def _module_has_file(modname) -> bool:
import importlib
return getattr(importlib.import_module(modname), '__file__', None) is not None Prevention
- Prefer --import-mode=importlib for namespace/PEP 420 packages.
- Add __init__.py to make packages regular.
When it happens
Trigger: Collecting a file that resolves to a namespace package (no __init__.py) whose __file__ is None; a module shadowed by a built-in or C extension; __init__.py-less package layouts combined with prepend import mode.
Common situations: Namespace packages in prepend/append mode; mixing importlib and prepend modes; a local file name colliding with a stdlib module.
Related errors
- Can't find module at location
- Could not resolve for
- {path}
- cannot create lockfile in
- cannot delete key in keywords dict
AI-assisted analysis of pytest-dev/pytest@0d6fbdeffa (2026-08-11).
Data as JSON: /api/errors/63557d91b8f84bfe.
Report an issue: GitHub.
Appendix: source
Thrown at src/_pytest/pathlib.py:650
if str(pkg_root) not in sys.path:
sys.path.append(str(pkg_root))
elif mode is ImportMode.prepend:
if str(pkg_root) != sys.path[0]:
sys.path.insert(0, str(pkg_root))
else:
assert_never(mode)
importlib.import_module(module_name)
mod = sys.modules[module_name]
if path.name == "__init__.py":
return mod
ignore = os.environ.get("PY_IGNORE_IMPORTMISMATCH", "")
if ignore != "1":
module_file = mod.__file__
if module_file is None:
raise ImportPathMismatchError(module_name, module_file, path)
if module_file.endswith((".pyc", ".pyo")):
module_file = module_file[:-1]
if module_file.endswith(os.sep + "__init__.py"):
module_file = module_file[: -(len(os.sep + "__init__.py"))]
try:
is_same = _is_same(str(path), module_file)
except FileNotFoundError:
is_same = False
if not is_same:
raise ImportPathMismatchError(module_name, module_file, path)
return mod
def _import_module_using_spec(View on GitHub (pinned to 0d6fbdeffa)