🔧 Error Fixes
· 2 min read

ModuleNotFoundError / ImportError — How to Fix It


ModuleNotFoundError: No module named 'requests'
ImportError: cannot import name 'xyz' from 'module'

Python can’t find the module you’re trying to import. It’s either not installed, installed in the wrong environment, or has a naming conflict.

Fix 1: Install the Package

# ❌ Module not installed
pip install requests

# If pip isn't the right one:
pip3 install requests
python3 -m pip install requests

Fix 2: Wrong Python Environment

# ❌ Installed in system Python, running in a venv (or vice versa)

# Check which Python you're using
which python3
python3 -c "import sys; print(sys.executable)"

# Check where packages are installed
pip3 show requests

# Activate your virtual environment first
source venv/bin/activate
pip install requests

Fix 3: Virtual Environment Not Activated

# ❌ Running without activating venv
python3 app.py  # Uses system Python

# ✅ Activate first
source venv/bin/activate  # Linux/Mac
.\venv\Scripts\activate   # Windows
python3 app.py

Fix 4: Circular Import

# ❌ a.py imports b.py, b.py imports a.py
# a.py
from b import helper  # 💥 ImportError

# ✅ Move shared code to a third file
# Or import inside the function
def my_function():
    from b import helper  # Lazy import

Fix 5: File Name Conflicts

# ❌ Your file is named the same as a module
# You have a file called "requests.py" in your project
import requests  # 💥 Imports YOUR file, not the package

# ✅ Rename your file
mv requests.py my_requests.py

Fix 6: Package Name ≠ Import Name

# ❌ Some packages have different install and import names
pip install Pillow        # Install name
import PIL                # Import name

pip install python-dotenv # Install name
import dotenv             # Import name

pip install opencv-python # Install name
import cv2                # Import name

Debugging

# Check if module is installed
python3 -c "import requests; print(requests.__file__)"

# List all installed packages
pip list | grep requests

# Check Python path
python3 -c "import sys; print('\n'.join(sys.path))"
📘