ModuleNotFoundError but pip says it is installed: you are not running the Python you think you are
verbatim error$ python src/main.py
Traceback (most recent call last):
File "/srv/app/src/main.py", line 4, in <module>
from fastapi import FastAPI
ModuleNotFoundError: No module named 'fastapi'
$ pip show fastapi | head -2
Name: fastapi
Version: 0.115.0
Problem
pip show insists the package is installed. The script insists otherwise:
$ python src/main.py
Traceback (most recent call last):
File "/srv/app/src/main.py", line 4, in <module>
from fastapi import FastAPI
ModuleNotFoundError: No module named 'fastapi'
$ pip show fastapi | head -2
Name: fastapi
Version: 0.115.0Reinstalling "fixed" it sometimes — by re-installing into whichever interpreter happened to run the script. The bug came back the next time anyone's PATH changed.
Root cause
pip and python are independent binaries that only agree by accident. The pip on PATH belongs to one interpreter (often a pyenv shim, Homebrew Python, or the system one); python resolves to another. The module exists in pip's environment and is missing in python's. The question is never "is fastapi installed" — it is "installed for which interpreter".
fix preview — first 1 of 2 lines (bash), truncated:
python -m pip show fastapi # installs/queries for THIS python
… 1 more line in the fix🔒 the fix — including 3 code blocks — is members-only. $1/mo unlocks everything.