pytest "import file mismatch" - Fix Duplicate Module / Cache Errors
pytest found two test files that resolve to the same module name, or stale bytecode caches that don’t match the source. Without package __init__.py files, identically named test files collide on import.
What this error means
Collection fails with import file mismatch, telling you a module imported from one path doesn’t match the cached one. It often appears after copying tests or running in a container over a previously-built checkout.
import file mismatch:
imported module 'test_utils' has this __file__ attribute:
/repo/a/test_utils.py
which is not the same as the test file we want to collect:
/repo/b/test_utils.py
HINT: remove __pycache__ / .pyc files and/or use a unique basenameCommon causes
Duplicate test module names without packages
Two test_utils.py files in different directories with no __init__.py both import as the top-level module test_utils, so pytest can’t tell them apart.
Stale __pycache__/.pyc files
Cached bytecode from a previous layout or a different checkout path no longer matches the source, triggering the mismatch on import.
How to fix it
Make test directories packages
Add __init__.py so identically-named files live in distinct importable packages.
touch tests/a/__init__.py tests/b/__init__.py
# now a.test_utils and b.test_utils are distinctClear stale caches
find . -name '__pycache__' -type d -prune -exec rm -rf {} +
find . -name '*.pyc' -delete
pytestOr use importlib import mode
The importlib import mode avoids the shared-top-level-name problem entirely.
[tool.pytest.ini_options]
addopts = "--import-mode=importlib"How to prevent it
- Give test directories
__init__.pyor use--import-mode=importlib. - Use unique test file basenames across directories.
- Don’t mount or cache stale
__pycache__into CI containers.