error python

Python ModuleNotFoundError

Understanding Python ModuleNotFoundError - raised when Python cannot find the module you are trying to import.

What It Means

ModuleNotFoundError (a subclass of ImportError, introduced in Python 3.6) is raised when Python cannot locate the module specified in an import statement. The error message reads: No module named 'module_name'.

Common Causes

  • Package is not installed (pip install needed)
  • Virtual environment is not activated
  • Package installed in a different Python version or environment
  • Module name is different from the package name (e.g., pip install Pillow, import PIL)
  • Local file has the same name as a standard library module (shadowing)
  • Running a script from the wrong directory
  • Package installed with pip but running with python3 (or vice versa)

How to Fix

Install the missing package

# Install with pip
pip install requests

# Ensure you're using the right pip
python3 -m pip install requests

# Common package name vs import name mismatches:
pip install Pillow          # import PIL
pip install opencv-python   # import cv2
pip install scikit-learn    # import sklearn
pip install python-dateutil # import dateutil
pip install PyYAML          # import yaml
pip install beautifulsoup4  # import bs4

Check your virtual environment

# Check if a virtual environment is active
which python
echo $VIRTUAL_ENV

# Create and activate a virtual environment
python3 -m venv venv
source venv/bin/activate  # Linux/macOS
# venv\Scripts\activate   # Windows

# Install dependencies
pip install -r requirements.txt

Fix module shadowing

# If your file is named 'json.py', 'email.py', 'random.py', etc.
# it will shadow the standard library module

# Check which module is being loaded
import json
print(json.__file__)  # Should be in the Python lib, not your project

# Fix: rename your file to something else
# json.py -> json_utils.py

Fix import path issues

# Check Python's module search path
import sys
print(sys.path)

# Add a directory to the search path
sys.path.insert(0, '/path/to/your/module')

# Better: install your package in development mode
# pip install -e .

Fix in Docker

FROM python:3.12-slim

WORKDIR /app

# Install dependencies first (for caching)
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .
CMD ["python", "app.py"]

Fix with pyproject.toml

# pyproject.toml - proper project structure
[project]
name = "myproject"
dependencies = [
    "requests>=2.28.0",
    "flask>=2.3.0",
]

# Install: pip install -e .

Verify installation

# Check if a module is installed and where it's located
import importlib
try:
    mod = importlib.import_module('requests')
    print(f"Found: {mod.__file__}")
    print(f"Version: {mod.__version__}")
except ModuleNotFoundError:
    print("Not installed")