ModuleNotFoundError: No module named 'X'
ID: python/modulenotfounderror
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 311 | active | — | — | — |
| 310 | active | — | — | — |
Root Cause
Almost always resolvable once the correct package name is identified and the correct Python environment is targeted. Failures persist when the module name and PyPI package name diverge significantly (e.g., 'cv2' vs 'opencv-python', 'sklearn' vs 'scikit-learn').
genericWorkarounds
-
92% success Install using the correct PyPI package name
Look up the correct package name on pypi.org or use 'pip install' with the known distribution name. Common mappings: cv2 -> opencv-python, sklearn -> scikit-learn, yaml -> PyYAML, PIL -> Pillow, attr -> attrs.
Sources: https://pypi.org/
-
85% success Verify and activate the correct virtual environment
Run 'which python' and 'pip list' to confirm you are in the expected environment. Activate with 'source /path/to/venv/bin/activate'. In Docker, ensure the pip install runs with the same Python used at runtime.
-
90% success Use pip with the target Python interpreter directly
Run 'python3.11 -m pip install <package>' to guarantee the package is installed into the correct interpreter's site-packages, avoiding ambiguity between multiple Python versions.
Dead Ends
Common approaches that don't work:
-
Running 'pip install X' where X is the import name, not the package name
65% fail
Many Python packages have PyPI distribution names that differ from their import names. For example, 'import cv2' requires 'pip install opencv-python', 'import sklearn' requires 'pip install scikit-learn', and 'import yaml' requires 'pip install PyYAML'. Using the import name returns 'no matching distribution found' or installs the wrong package entirely.
-
Adding sys.path.append('/path/to/module') as a permanent fix
78% fail
sys.path.append is a runtime-only modification that does not persist across sessions, scripts, or containers. It also introduces fragile absolute paths that break on deployment. It masks the real issue: the package is either not installed or installed in a different environment.
-
Installing the package globally with 'sudo pip install X'
71% fail
Installing globally does not affect virtualenv or Docker-isolated Python environments. The global site-packages is invisible to activated virtual environments unless --system-site-packages was set at creation. On modern Linux distros, PEP 668 blocks global installs entirely with 'externally-managed-environment' errors.