pytest
Python
ImportError
troubleshooting
PATH issue

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.

Browse interview questions

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.

bash
python -m pytest -q

This avoids accidentally using a globally installed pytest tied to another interpreter.

Check interpreter paths:

bash
which python
python -c "import sys; print(sys.executable)"
python -m pytest --version

Use a package layout that supports absolute imports

A src/ layout with installable package metadata is robust.

text
1project/
2  pyproject.toml
3  src/
4    mypkg/
5      __init__.py
6      core.py
7  tests/
8    test_core.py

Install editable package in your virtualenv:

bash
python -m pip install -e .
python -m pytest

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.

python
# avoid in tests:
# sys.path.append("..")

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.

toml
[tool.pytest.ini_options]
addopts = "-ra"
pythonpath = ["src"]

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 pytest from a different Python environment than your project virtualenv.
  • Executing tests from subdirectories that alter relative import resolution unexpectedly.
  • Relying on ad hoc sys.path edits instead of proper package installation.
  • Naming files or folders after stdlib modules and shadowing expected imports.
  • Skipping __init__.py where 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:

text
11. Prepare deterministic sample input
22. Run expected-success scenario
33. Run expected-edge scenario
44. Run expected-failure scenario
55. Assert output schema and key values
66. Record one performance or reliability metric

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
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track 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.

Browse interview questions

All Rights Reserved.