Skip to content
Latchkey

pytest "--import-mode=importlib" Changes Imports and Breaks Tests in CI

pytest’s --import-mode controls how test modules are imported. The default prepend mode inserts directories onto sys.path; importlib mode does not, so tests that relied on implicit sys.path entries fail to import the package under test.

What this error means

After setting --import-mode=importlib (or upgrading to a config that defaults to it), tests fail at collection with ModuleNotFoundError for the package under test or a conftest, even though the files exist. Switching back to prepend, or installing the package, fixes it.

pytest output
ERROR collecting tests/test_api.py
ModuleNotFoundError: No module named 'myapp'
# worked under --import-mode=prepend, fails under importlib

Common causes

importlib mode does not modify sys.path

Unlike prepend/append, importlib mode imports tests without inserting their directories onto sys.path. Code relying on that implicit path no longer resolves the package.

Package not installed, only on an implicit path

If the project was never installed (pip install -e .) and relied on prepend adding the rootdir, importlib mode has no path to it.

How to fix it

Install the project so imports resolve regardless of mode

An editable install puts the package on sys.path properly, which importlib mode (and a src-layout) expects.

Terminal
pip install -e .
pytest --import-mode=importlib

Set the import mode explicitly and consistently

Pin the mode in config so local and CI behave the same.

pyproject.toml
[tool.pytest.ini_options]
addopts = "--import-mode=importlib"
pythonpath = ["src"]   # if not installing the package

How to prevent it

  • Install the project (editable is fine) rather than relying on implicit sys.path.
  • Pin --import-mode in config so it is consistent across environments.
  • Adopt a src-layout with importlib mode for clean import isolation.

Related guides

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