๐Ÿ”ง Error Fixes
ยท 5 min read
Last updated on

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. This is one of the most common Python errors, and it has several distinct causes โ€” from missing packages to environment mismatches to naming conflicts.

Why this happens

When you write import requests, Python searches for the module in this order:

  1. The current directory
  2. Directories in PYTHONPATH environment variable
  3. The standard library
  4. Installed packages (site-packages)

If the module isnโ€™t found in any of these locations, Python raises ModuleNotFoundError. If the module is found but the specific name youโ€™re importing from it doesnโ€™t exist, you get ImportError.

Fix 1: Install the missing package

The most common cause โ€” the package simply isnโ€™t installed.

# Install with pip
pip install requests

# If you have multiple Python versions, be explicit
pip3 install requests
python3 -m pip install requests

# For a specific version
pip install requests==2.31.0

# From a requirements file
pip install -r requirements.txt

Verify itโ€™s installed:

pip show requests
# Shows: Name, Version, Location, etc.
# If "WARNING: Package(s) not found" โ€” it's not installed

Fix 2: Wrong Python environment (most frustrating)

You installed the package, but Python is using a different interpreter that doesnโ€™t have it.

# Check which Python is running
which python3
# /usr/bin/python3 โ† system Python

python3 -c "import sys; print(sys.executable)"
# /usr/bin/python3

# Check where pip installs to
pip3 show requests | grep Location
# /home/user/.local/lib/python3.11/site-packages

# But your script might be using a different Python!

The fix: Always use python -m pip to ensure pip matches your Python:

# This guarantees pip installs for the same Python that runs your code
python3 -m pip install requests

# Or in a virtual environment (best practice)
python3 -m venv .venv
source .venv/bin/activate
pip install requests
python3 app.py  # Uses .venv's Python with requests installed

Fix 3: Virtual environment not activated

You created a venv and installed packages there, but youโ€™re running the script with system Python.

# โŒ Running without activating
python3 app.py  # Uses system Python โ€” no packages from venv

# โœ… Activate first
source .venv/bin/activate    # Linux/Mac
.\.venv\Scripts\activate     # Windows PowerShell
.venv\Scripts\activate.bat   # Windows CMD

# Now python3 and pip point to the venv
python3 app.py  # Uses venv Python with all installed packages

# โœ… Or run directly with the venv's Python
.venv/bin/python3 app.py  # No activation needed

IDE tip: In VS Code, select the interpreter (Ctrl+Shift+P โ†’ โ€œPython: Select Interpreterโ€) and choose your venv. This ensures the terminal and debugger use the right Python.

Fix 4: File name conflicts with module names

If you have a file named the same as a package, Python imports your file instead of the package.

# โŒ You have a file called "requests.py" in your project
# Python imports YOUR file, not the pip package
import requests  # ImportError or unexpected behavior

# โŒ Other common conflicts:
# email.py, json.py, random.py, test.py, typing.py, collections.py

Fix: Rename your file to something that doesnโ€™t conflict:

mv requests.py http_client.py
mv email.py email_sender.py
mv test.py test_app.py

# Also delete the cached .pyc file
rm -rf __pycache__

How to detect: If import requests works in the Python REPL but not in your project, you likely have a naming conflict.

Fix 5: Package name โ‰  import name

Some packages have different names for pip install vs import. This trips up everyone.

pip installimport as
PillowPIL
python-dotenvdotenv
opencv-pythoncv2
scikit-learnsklearn
beautifulsoup4bs4
python-dateutildateutil
PyYAMLyaml
Pygmentspygments
# โŒ Wrong install name
pip install PIL  # Package doesn't exist!

# โœ… Correct
pip install Pillow
python3 -c "from PIL import Image"  # Works

Fix 6: Circular imports

Two modules importing each other creates a circular dependency. Python canโ€™t resolve it.

# โŒ a.py imports from b.py, b.py imports from a.py
# a.py
from b import helper_b  # ImportError!

# b.py
from a import helper_a

Fixes:

# โœ… Option 1: Import inside the function (lazy import)
def my_function():
    from b import helper_b  # Only imported when function is called
    return helper_b()

# โœ… Option 2: Move shared code to a third module
# shared.py โ€” no imports from a or b
def shared_helper():
    pass

# โœ… Option 3: Import the module, not the name
import b  # Import the module
b.helper_b()  # Access the name later

See Python ImportError Circular โ€” Fix for more patterns.

Fix 7: Relative import errors

# โŒ Relative import in a script run directly
from .utils import helper  # ImportError: attempted relative import with no known parent package

# โœ… Option 1: Use absolute imports
from mypackage.utils import helper

# โœ… Option 2: Run as a module
python3 -m mypackage.main  # Instead of python3 mypackage/main.py

Relative imports only work when the file is part of a package (has __init__.py) and is imported, not run directly.

Fix 8: Missing __init__.py (Python packages)

For Python to recognize a directory as a package, it needs an __init__.py file (can be empty).

myproject/
โ”œโ”€โ”€ main.py
โ”œโ”€โ”€ utils/          โ† directory
โ”‚   โ”œโ”€โ”€ __init__.py โ† REQUIRED (can be empty)
โ”‚   โ””โ”€โ”€ helpers.py
# Without __init__.py:
from utils.helpers import my_func  # ModuleNotFoundError

# With __init__.py:
from utils.helpers import my_func  # Works

Note: In Python 3.3+, โ€œnamespace packagesโ€ work without __init__.py, but itโ€™s still best practice to include it for clarity.

Debugging checklist

import sys

# 1. Which Python am I using?
print(sys.executable)

# 2. Where does Python look for modules?
print('\n'.join(sys.path))

# 3. Is the package installed?
import importlib
spec = importlib.util.find_spec('requests')
print(spec)  # None = not found

# 4. Where is the package?
import requests
print(requests.__file__)

FAQ

Why does pip install succeed but import still fails?

pip installed to a different Python than the one running your script. Use python3 -m pip install to ensure they match, or check which python3 vs pip3 show <package> | grep Location.

How do I fix this in Docker?

Make sure your Dockerfile installs packages for the same Python that runs the app:

RUN pip install --no-cache-dir -r requirements.txt
CMD ["python3", "app.py"]

Why does it work in Jupyter but not in my script?

Jupyter might be using a different kernel (different Python installation). Check with !which python in a Jupyter cell and compare to your terminalโ€™s which python3.

How do I fix โ€œImportError: cannot import name X from Yโ€?

This means the module exists but doesnโ€™t have the name youโ€™re importing. Common causes: wrong version of the package (the function was added in a newer version), typo in the name, or youโ€™re importing from your own file that shadows the package.

๐Ÿ“˜