Python ImportError & ModuleNotFoundError — Fix Guide

Fix Python ImportError and ModuleNotFoundError. Covers virtual environments, pip install, relative imports, circular imports, and sys.path configuration.

Python Exceptions

Detailed Explanation

Python ImportError & ModuleNotFoundError

ImportError occurs when Python cannot find or load a module. ModuleNotFoundError (a subclass of ImportError since Python 3.6) is raised specifically when the module itself cannot be located.

Common Causes

1. Package not installed:

# Check if package is installed
pip list | grep package-name

# Install it
pip install package-name

# Install from requirements
pip install -r requirements.txt

2. Virtual environment not activated:

# Check which Python is being used
which python
# /usr/bin/python3 <- system Python, venv not active

# Activate virtual environment
source venv/bin/activate  # Linux/macOS
.\venv\Scripts\activate  # Windows

which python
# /project/venv/bin/python3 <- correct

3. Relative import issues:

# Project structure:
# myproject/
#   __init__.py
#   main.py
#   utils/
#     __init__.py
#     helpers.py

# In helpers.py:
from ..main import app  # Works only when run as package

# Running directly fails:
# python myproject/utils/helpers.py  # ImportError!

# Run as module instead:
# python -m myproject.utils.helpers  # Works

4. Circular imports:

# a.py
from b import func_b  # Tries to import b
def func_a(): pass

# b.py
from a import func_a  # Tries to import a (circular!)
def func_b(): pass

# Fix: import inside function or restructure
def func_b():
    from a import func_a  # Deferred import
    func_a()

5. Wrong Python version:

# Package installed for Python 3.9 but running 3.11
pip3.11 install package-name

# Or use python -m pip to match the interpreter
python3.11 -m pip install package-name

Debugging Import Issues

import sys

# Check where Python looks for modules
print(sys.path)

# Check module location
import package_name
print(package_name.__file__)

# Check Python version
print(sys.version)

Best Practices

  1. Always use virtual environments
  2. Pin dependencies in requirements.txt or pyproject.toml
  3. Use python -m pip install to ensure correct interpreter
  4. Avoid circular imports by restructuring or using deferred imports
  5. Test imports in CI to catch issues early

Use Case

Import errors are the second most common Python exception after KeyError. They appear during project setup, dependency upgrades, deployment to new environments, and when working with complex package structures. Understanding virtual environments, relative imports, and circular import resolution is fundamental for productive Python development.

Try It — Error Code Reference

Open full tool