Last modified: May 10, 2025 By Alexander Williams

Troubleshooting Python Import Errors

Python import errors can be frustrating. They often stop your code from running. This guide covers common issues and solutions.

1. ModuleNotFoundError

ModuleNotFoundError occurs when Python can't find the module. This usually means the module isn't installed.


import non_existent_module  # Raises ModuleNotFoundError


ModuleNotFoundError: No module named 'non_existent_module'

Solution: Install the missing package using pip.


pip install package_name

2. ImportError

ImportError happens when Python finds the module but can't load it. This might be due to missing dependencies.


from existing_module import missing_name  # Raises ImportError

Check your Python import best practices to avoid such issues.

3. Circular Imports

Circular imports occur when two modules import each other. This creates a loop.


# module_a.py
import module_b

# module_b.py
import module_a

Solution: Restructure your code or use local imports. Learn more about managing import side effects.

4. Relative Import Problems

Relative imports can fail when running modules as scripts. Use absolute imports when possible.


from .submodule import function  # Might fail when run as script

For more details, see our Python relative imports guide.

5. PYTHONPATH Issues

Python might not find modules if they're not in your path. Check your PYTHONPATH environment variable.


echo $PYTHONPATH

You can modify it temporarily in Python:


import sys
sys.path.append('/path/to/module')

6. Name Conflicts

Having a local file with the same name as a package causes conflicts.


# Having a file named 'math.py' will shadow the standard library

Solution: Rename your local files to avoid standard library names.

7. __init__.py Missing

In Python versions before 3.3, packages need __init__.py files. Without them, Python won't recognize the directory as a package.


my_package/
    module.py  # Without __init__.py, this isn't a proper package

8. Version Conflicts

Different Python versions might handle imports differently. Check your Python version with:


python --version

9. Using importlib for Dynamic Imports

For advanced cases, use importlib.import_module():


import importlib
module = importlib.import_module('module_name')

Learn more about dynamic imports in Python.

Conclusion

Import errors are common but solvable. Most issues stem from path problems or missing files. Always check your Python path and module structure first.

For complex projects, follow established import patterns. This will save you time debugging import-related issues.