PythonMastery
reference 3 min read · lesson 24 of 45 in Errors

ModuleNotFoundError: No module named 'X'

1 · The lesson

read

What this error means

The import machinery walked every entry in sys.path — your script's directory, the standard library, site-packages — and could not find a package or module called X. ModuleNotFoundError is a subclass of ImportError introduced in Python 3.6 to distinguish "the module doesn't exist" from "the module exists but failed to import".

When you see it

text
Traceback (most recent call last):
  File "app.py", line 1, in <module>
    import requests
ModuleNotFoundError: No module named 'requests'

Why it happens

Three common causes: (1) the package is genuinely not installed in this Python; (2) it is installed, but for a different Python — your shell's pip does not point at the same interpreter as python; (3) the import name does not match the package name on PyPI, so you installed the wrong thing.

How to fix it

Option 1 — install it in the right interpreter. Always install via python -m pip to guarantee pip belongs to the Python you're running.

bash
python -m pip install requests

Compare with the wrong way (pip install requests), which may install into a completely different Python.

Option 2 — check the virtual environment is active. A bare pip install outside an activated venv often goes into the system Python while your editor runs the venv's Python.

bash
# Windows
.venv\Scripts\activate
# macOS / Linux
source .venv/bin/activate

python -m pip install requests

Option 3 — check the import name. PyPI distribution name and import name often differ:

You installYou import
scikit-learnsklearn
beautifulsoup4bs4
pillowPIL
pyyamlyaml
python-dotenvdotenv
opencv-pythoncv2

Option 4 — verify which Python you're using. Mismatch between shell python and editor Python is the #1 cause on Windows.

bash
python -c "import sys; print(sys.executable)"
python -m pip show requests

If the second command says "WARNING: Package(s) not found", requests is not installed in that Python regardless of what other pips claim.

When you'd actually see this in real code

  • You cloned a repo, ran python app.py, and forgot to install requirements.txt.
  • You typed import scikit-learn instead of import sklearn.
  • VS Code is running the global Python but your terminal has the venv activated, or vice versa.
  • You're inside a Jupyter kernel that points at a different Python than pip install used.
  • ImportError: cannot import name 'X' from 'Y' — the module exists, but the specific name inside it doesn't. See error-importerror-cannot-import.
  • ModuleNotFoundError: No module named 'X.Y'; 'X' is not a package — X is a single module, not a package, so it has no submodules.

See Also