PATH issue with pytest 'ImportError No module named ...'
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
A common pytest failure is ImportError: No module named ... even though the module imports correctly in an interactive shell. This usually comes from how Python resolves modules when tests run from different working directories or environments. The root causes are often project layout issues, missing package initialization, conflicting local names, or invoking the wrong interpreter. The reliable fix is to make imports explicit, standardize test execution entry points, and ensure package installation behavior matches your CI setup. Treating import resolution as part of project configuration prevents recurring flaky test runs.
Core Sections
Run pytest from the project root with the correct interpreter
Always call pytest via the target Python executable.
This avoids accidentally using a globally installed pytest tied to another interpreter.
Check interpreter paths:
Use a package layout that supports absolute imports
A src/ layout with installable package metadata is robust.
Install editable package in your virtualenv:
Then tests can safely use from mypkg.core import ....
Avoid brittle path hacks in tests
Appending to sys.path inside tests can hide real packaging problems.
If temporary path adjustment is unavoidable, centralize it in conftest.py and document why.
Configure pytest import mode when needed
In some projects, import mode settings help resolve package ambiguity.
Prefer packaging correctness first, then use config as a small compatibility layer.
Validate in CI the same way as local
Use the same python -m pytest invocation locally and in CI. Mismatched commands are a major source of "works on my machine" import bugs.
Common Pitfalls
- Running global
pytestfrom a different Python environment than your project virtualenv. - Executing tests from subdirectories that alter relative import resolution unexpectedly.
- Relying on ad hoc
sys.pathedits instead of proper package installation. - Naming files or folders after stdlib modules and shadowing expected imports.
- Skipping
__init__.pywhere package semantics are required.
Verification Workflow
After implementing the main approach, run a short verification loop that proves behavior on realistic and adversarial inputs. Start with a small happy-path sample that should always pass, then add one edge case and one failure case that should be rejected or handled gracefully. Capture concrete outputs instead of relying on visual inspection alone. For operational code, record one measurable signal such as runtime, memory use, or error count so you can compare before and after future refactors.
Use this quick template during local development and CI:
This discipline catches most regressions caused by dependency upgrades, environment differences, or hidden assumptions in helper functions. It also makes handoffs easier because another engineer can reproduce behavior quickly without reverse-engineering your intent from source code alone.
Deployment Notes
Before rolling this pattern into production, add one small automated regression check tied to your most critical user path. Keep the check deterministic and fast, and run it on every dependency or configuration change. This extra guardrail catches subtle behavior drift that static review often misses, especially when environments differ between local machines and CI runners.
Summary
Most pytest import errors are environment and package layout issues, not pytest defects. Use python -m pytest, adopt a consistent installable package structure, and avoid per-test path hacks. Keep local and CI invocation identical so import behavior is reproducible. Once import resolution is explicit and standardized, these failures usually disappear.
Related reading
- pdb cannot break in another thread?
- Peak-finding algorithm for Python/SciPy
- Perform commands over ssh with Python
- Permanently add a directory to PYTHONPATH?
- Populate a database with TestContainers in a SpringBoot integration test
- Populating Spring @Value during Unit Test
- PDOException “could not find driver”
- Perceptron learning algorithm not converging to 0
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.