Fixing ModuleNotFoundError: No module named
Troubleshooting / module-not-found-error.html
The causes and a diagnosis/fix procedure for Python's most common import error. In most cases it is a mismatch between the interpreter that runs and the one that installed.
"I ran pip install, why does it still say No module named?"
ModuleNotFoundError: No module named 'xxx' is the most common Python error. The good news is that most cases share one cause: the Python that runs the code is not the Python where the package was installed.
Symptom
$ python myscript.py
ModuleNotFoundError: No module named 'requests'
But you definitely ran pip install requests. This is where most people get stuck and start searching.
Causes (most frequent first)
- Environment mismatch: a virtual environment is active in one terminal, but you ran a different Python
- Never actually installed:
pip3andpython3point to different places (multiple Pythons on the machine) - Relative import issue: inside a package you wrote
import xinstead offrom . import x - No pip at all: some minimal images or freshly created environments lack pip
Diagnose in 30 seconds
These commands show which Python this shell uses and whether the package is present.
# 1) Which Python are we using?
python3 -c "import sys; print(sys.executable)"
# 2) Is the package in this Python?
python3 -c "import importlib.util as u; print(u.find_spec('requests'))"
# 3) Which Python is pip attached to?
python3 -m pip --version
If find_spec returns None, the package really is not in that Python. It is a location problem, not an install problem.
Fix
- In projects that use a virtual environment, activate it and run again.
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install requests
python myscript.py
- Without a virtual environment, install into the exact Python you confirmed above.
python3 -m pip install requests
- If pip itself is missing, bootstrap it with
python3 -m ensurepip --upgrade, or on Debian/Ubuntu installpython3-pip python3-venv.
Habits to avoid
sudo pip install— can damage the system Python; use a virtual environment instead.- Reinstalling blindly on every error — the three diagnosis lines above are faster than reinstalling.
- Sharing one virtual environment across projects — a classic source of version conflicts.
Related situations
- Inside Docker, the same error means the package was not installed in the image, or a different Python was used at install vs. run time. Check the build log for the actual
pip installstep. - Hitting this right after scaffolding a framework like FastAPI is usually the environment-mismatch case above.
Sources
- stackoverflow ImportError: No module named — Old question, same root cause today
- stackoverflow Relative imports and ModuleNotFoundError — Package layout
- Official docs Official venv docs — Virtual environments
Verified date indicates freshness. Check applicability conditions for older material.