debugpythonMajorpending
Debug: Python import errors and ModuleNotFoundError
Viewed 0 times
modulenotfounderrorimporterrorsys.pathcircular importname shadowing
Error Messages
Problem
Python raises ModuleNotFoundError or ImportError when importing modules that should exist.
Solution
Systematic diagnosis of import failures:
Common causes and fixes:
# 1. Check which Python is running
which python3
python3 --version
# 2. Check if package is installed
python3 -m pip list | grep package_name
python3 -m pip show package_name # Shows location
# 3. Check sys.path (where Python looks for modules)
python3 -c "import sys; print('\n'.join(sys.path))"
# 4. Check if you're in the right virtualenv
echo $VIRTUAL_ENV # Should show venv path
python3 -c "import sys; print(sys.prefix)" # Should match venvCommon causes and fixes:
# Cause 1: Wrong Python / not in venv
# Fix: Activate venv first
source .venv/bin/activate
pip install missing_package
# Cause 2: Package name != import name
# pip install Pillow, but: import PIL
# pip install python-dateutil, but: import dateutil
# pip install beautifulsoup4, but: import bs4
# pip install scikit-learn, but: import sklearn
# Cause 3: Circular imports
# a.py imports from b.py which imports from a.py
# Fix: Move shared code to a third module c.py
# Or: Use lazy imports inside functions
def my_function():
from other_module import helper # Import at use time
return helper()
# Cause 4: Missing __init__.py (Python < 3.3)
# mypackage/__init__.py must exist for package imports
# Cause 5: Name shadowing
# Your file named 'json.py' shadows stdlib json
# Fix: Rename your file!
# Cause 6: Relative import outside package
# from .utils import helper # Only works inside a package
# Fix: Use absolute imports or run with -m
python3 -m mypackage.module # Instead of python3 mypackage/module.pyWhy
Python's import system searches sys.path in order. Most errors come from wrong environment, name conflicts, or circular dependencies.
Context
Python projects with module import issues
Revisions (0)
No revisions yet.