Skip to content

How to Fix Python ImportError Module Not Found

DodaTech 2 min read

In this tutorial, you'll learn about How to Fix Python ImportError Module Not Found. We cover key concepts, practical examples, and best practices.

The Problem

You run a Python script and get:

Traceback (most recent call last):
  File "script.py", line 1, in <module>
    import requests
ModuleNotFoundError: No module named 'requests'

Or:

ImportError: cannot import name 'helper' from 'mymodule' (/path/to/mymodule.py)

Python cannot find the module because it is not installed, the virtual environment is not activated, or there is a circular import.

Quick Fix

Step 1: Install the missing module

pip install requests

Or use pip3:

pip3 install requests

Step 2: Activate the virtual environment

If you installed the package in a virtual environment but forgot to activate it:

# Check if a venv exists
ls venv/bin/activate

# Activate it
source venv/bin/activate

# Verify the module is installed
pip list | grep requests

Step 3: Check the Python version

Sometimes pip installs for Python 2 but you run Python 3:

# Install for Python 3 explicitly
python3 -m pip install requests

Step 4: Fix circular imports

If the error is cannot import name, check for circular imports:

# a.py
from b import helper  # b.py imports from a.py indirectly

Refactor shared code into a third module:

# common.py -- shared code
# a.py -- imports from common
# b.py -- imports from common

Step 5: Check PYTHONPATH

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

If your module's directory is not in the path, add it:

export PYTHONPATH=/path/to/my/module:$PYTHONPATH

Alternative Solutions

Reinstall the package if it is corrupted:

pip install --force-reinstall requests

Verify Your Python Environment

python3 --version
# Python 3.10.12
pip list | grep requests
# requests            2.31.0

Check your Python version and installed packages before debugging. Many errors are caused by version mismatches between development and production environments. Using a virtual environment with pinned dependencies prevents these surprises.

Additional Troubleshooting

# Check the error message and stack trace for more context
echo "Review the full error output to identify the root cause"

If the above steps do not resolve the issue, examine the complete error message and stack trace. Often the key detail is in the middle of the traceback rather than the final line. Search for the error message in the project documentation or issue tracker for additional solutions.

Prevention

  • Always use a virtual environment for each project.
  • Create a requirements.txt file and keep it updated.
  • Activate the virtual environment in your editor.
  • Structure projects to avoid circular imports from the start.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro