Skip to content
Latchkey

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.

pytest output
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 basename

Common 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.

Terminal
touch tests/a/__init__.py tests/b/__init__.py
# now a.test_utils and b.test_utils are distinct

Clear stale caches

Terminal
find . -name '__pycache__' -type d -prune -exec rm -rf {} +
find . -name '*.pyc' -delete
pytest

Or use importlib import mode

The importlib import mode avoids the shared-top-level-name problem entirely.

pyproject.toml
[tool.pytest.ini_options]
addopts = "--import-mode=importlib"

How to prevent it

  • Give test directories __init__.py or use --import-mode=importlib.
  • Use unique test file basenames across directories.
  • Don’t mount or cache stale __pycache__ into CI containers.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →