Python ImportError
Python found the module but failed to load it due to a dependency or attribute issue.
Explanation
ImportError occurs when Python finds the module but cannot import it due to issues during the loading process. This is different from ModuleNotFoundError where the module isn't found at all. Common causes include a missing dependency that the module requires, circular imports between modules, syntax errors within the imported module, name conflicts between local files and installed packages, or the module trying to import something that doesn't exist.
Common Causes
- Missing dependency within the module
- Circular imports
- Name conflict with local file
- Module version incompatibility
- Syntax error in imported module
Solution
Read the full error message carefully - it usually indicates exactly what import within the module failed. Install any missing dependencies listed in the error. Check for circular imports and restructure code to avoid them. Verify the module version is compatible with your Python version. Use absolute imports instead of relative imports to avoid confusion. Check that local files don't shadow installed package names.
Code Example
# Circular import causes ImportError
# module_a.py
from module_b import some_function # imports b
def func_a():
pass
# module_b.py
from module_a import func_a # tries to import a while a is loading
# Fix: restructure to avoid circular imports
# module_a.py
def func_a():
from module_b import some_function # import inside function
some_function()
# Missing dependency in installed package
# ImportError: cannot import name 'X' from 'Y'
# Fix: pip install --upgrade Y
# Name conflict: file named requests.py in your project
# Python imports YOUR file instead of the requests library
# Fix: rename your file
Error Information
Language
python
Difficulty
Intermediate
Views
11
Related Errors
Python
Python RecursionError
The function calls itself too many times, exceeding the maximum recursion depth.
Python
Python ValueError
A function received an argument of correct type but inappropriate value.
Python
Python EOFError
The input() function encountered end-of-file (no more data to read).
Python
Python TabError
The code uses inconsistent indentation by mixing tabs and spaces.