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

ModuleNotFoundError: No module named 'X'

1 · The lesson

read

What this error means

Python searched every folder 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

There are three common causes. (1) The package is not installed in this Python. (2) It is installed, but for a different Python, because 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 with python -m pip. This makes sure 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 that 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. The name you install from PyPI and the name you import are often different:

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

Option 4: check which Python you're using. On Windows, the most common cause is that the python in your shell is not the Python your editor runs.

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, whatever other copies of pip say.

When you'd see this in real code

  • You cloned a repo, ran python app.py, and forgot to install requirements.txt.
  • You installed scikit-learn but imported it as import scikit_learn (its import name is 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

Found this useful? Share it with a friend who’s learning Python.