error python
Python ImportError
Understanding Python ImportError - raised when an import statement fails to find the module or cannot load a specific name from a module.
What It Means
ImportError is raised when an import statement has trouble loading a module. In Python 3.6+, ModuleNotFoundError (a subclass of ImportError) is raised when the module itself cannot be found. ImportError is now primarily raised when a specific name cannot be imported from an existing module.
The most common form is: ImportError: cannot import name 'X' from 'module'.
Common Causes
- Trying to import a name that doesn’t exist in the module
- Circular imports between modules
- Version mismatch (the installed version doesn’t have the expected function/class)
- Importing from the wrong module
- Module’s
__init__.pydoesn’t export the expected name - C extension module failed to compile during installation
How to Fix
Check what’s available in the module
# List all available names in a module
import some_module
print(dir(some_module))
# Check the module version
print(some_module.__version__)
Fix “cannot import name” errors
# Error: ImportError: cannot import name 'function_x' from 'module'
# Check if the name exists in a submodule
from module.submodule import function_x # Try submodule
# Check if the API changed in a newer version
# Old version:
from werkzeug import cached_property
# New version:
from werkzeug.utils import cached_property
Fix circular imports
# file_a.py
from file_b import func_b # Circular!
def func_a():
return func_b()
# file_b.py
from file_a import func_a # Circular!
def func_b():
return func_a()
# Fix Option 1: Import inside the function
# file_a.py
def func_a():
from file_b import func_b # Deferred import
return func_b()
# Fix Option 2: Restructure into a third module
# shared.py - move shared code here
Fix version-specific imports
# Handle different versions gracefully
try:
from collections import Mapping # Python < 3.10
except ImportError:
from collections.abc import Mapping # Python >= 3.10
Reinstall the package
# Reinstall to fix corrupted or incomplete installations
pip install --force-reinstall package_name
# Install a specific version
pip install package_name==2.0.0
# Check what's installed
pip show package_name
pip list | grep package_name
Fix C extension import errors
# If the error mentions .so or .pyd files
pip install --no-cache-dir --force-reinstall package_name
# Install build dependencies
sudo apt-get install python3-dev build-essential
# Reinstall
pip install --force-reinstall numpy
Related Errors
- Python ModuleNotFoundError - The module itself cannot be found (subclass of ImportError).
- Python AttributeError - Accessing an attribute that doesn’t exist on an imported module.