pytest importmode default remains prepend while importlib is recommended
0 reputation · 01 Jan 2023, 17:18 UTC
0 reputation · 01 Jan 2023, 17:18 UTC
The pytest project currently ships with importmode=prepend as the default, even though importlib has been the recommended mode since version 7.0.
This default preserves backward compatibility for test suites that rely on sys.path manipulation, but it creates friction for new projects using namespace packages or a src/ layout, which must explicitly set importmode=importlib in pytest.ini or via --import-mode.
The core team has not announced a target release for changing the default, and the migration path for existing suites remains undefined.
importlib?There is currently no official target release date for changing the default importmode from prepend to importlib. Because prepend modifies sys.path directly, switching the default would be a breaking change for legacy test suites that rely on implicit path resolution rather than proper package installation.
The friction experienced by new projects stems from how pytest locates your code:
sys.path. This is convenient for simple layouts but can cause "shadowing," where a local folder accidentally overrides an installed library of the same name.importlib machinery to load modules. This is the modern standard, especially for src/ layouts and namespace packages, as it avoids polluting the global path.If you are using a src/ layout or namespace packages, you should explicitly opt into importlib now rather than waiting for a default change. Use one of the following methods:
Add the setting to your pytest.ini or pyproject.toml to ensure consistency across all developer environments and CI/CD pipelines.
# pytest.ini
[pytest]
import_mode = importlib
Or for pyproject.toml:
# pyproject.toml
[tool.pytest.ini_options]
import_mode = "importlib"
To verify if importlib resolves your imports correctly without changing your config, run:
pytest --import-mode=importlib
While a formal "compatibility shim" has not been announced, the current guidance for projects that cannot migrate immediately is to explicitly define import_mode = prepend in their configuration. This locks the behavior and prevents the suite from breaking when the pytest core team eventually updates the default.
Diagnostic Note: To provide more specific migration advice, it is necessary to know if your project uses a src/ layout or a flat layout (where the package resides in the root directory).
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.