pytest-dev/pytest · error · ImportPathMismatchError
{module_name}, {module_file}, {path}
Error message
{module_name}, {module_file}, {path} What it means
In prepend/append import mode, after importing the module pytest compares its __file__ against the requested path. If module.__file__ is None (the module has no on-disk file, e.g. a built-in, frozen, or namespace module), it raises ImportPathMismatchError to avoid silently binding the wrong module.
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 98b357f69e)
Solutions
- Set PY_IGNORE_IMPORTMISMATCH=1 to skip the mismatch check
- Rename the file so its module name does not collide with a built-in/frozen module
- Fix the package layout so the module resolves to a real .py file
Example fix
// before # file named enum.py colliding with stdlib enum // after mv tests/enum.py tests/test_enum.py
Defensive patterns
Strategy: fallback
Validate before calling
import os
def should_skip_mismatch_check():
return os.environ.get('PY_IGNORE_IMPORTMISMATCH', '') == '1' Try / catch
try:
mod = import_path(path, mode='prepend')
except ImportPathMismatchError:
os.environ['PY_IGNORE_IMPORTMISMATCH'] = '1'
mod = import_path(path, mode='prepend') Prevention
- Avoid naming test files after built-in or frozen modules
- Set PY_IGNORE_IMPORTMISMATCH=1 only when the layout intentionally yields a None __file__
When it happens
Trigger: import_path in prepend/append mode resolves module_name to a module whose __file__ is None, then tries the mismatch check at pathlib.py:648-650 and raises. PY_IGNORE_IMPORTMISMATCH is not set.
Common situations: A test/conftest file whose name collides with a built-in or frozen module; namespace package resolving to a module without a file; exotic import hooks.
Related errors
- Can't find module {module_name} at location {path}
- {path}
- --pdbcls: could not import {value!r}: {exc}
- module or package not found: {arg} (missing __init__.py?)
- import error in {used}: {ex}
AI-assisted analysis of pytest-dev/pytest@98b357f69e (2026-08-04).
Data as JSON: /data/errors/0bbe69afd994aa06.json.
Report an issue: GitHub.