ImportError: Cannot Import Name — Causes and Fixes
Verify that the requested symbol exists in the target module, eliminate circular imports by refactoring dependencies, and ensure no local file shadows the library.
Root Cause Analysis
This error occurs when Python successfully locates and loads a target module file, but cannot find the specific class, function, or variable requested in the from module import name statement.
1. Typographical Errors or Removed API Symbols
The most straightforward cause is a misspelling of the symbol name, or attempting to import a function that was deprecated and removed in a newer version of the library (e.g. from sklearn.cross_validation import train_test_split).
2. Circular Import Dependencies
When module a.py imports module b.py while b.py simultaneously imports a symbol from a.py, Python enters a circular import loop. Because a.py has not finished compiling its global namespace when b.py executes, Python raises ImportError: cannot import name 'X' from partially initialized module.
3. Local File Shadowing
Creating a local script with the same name as a standard library module or third-party package (e.g. creating email.py or requests.py in your project folder) causes Python to import your empty local file rather than the authentic package.
4. Missing __all__ Exports
If a package defines __all__ in __init__.py without including sub-modules, explicit named imports may fail.
Reproduction Code (MCVE)
# Simulating importing a non-existent symbol from standard math module
from math import non_existent_trigonometric_function
Solution 1: Import Valid Existing Symbols
Verify the module's exported attributes using dir(module) and import the correct symbol name.
import math
# Verify and import valid attributes
from math import sin, cos, pi
print(f'sin(pi/2) = {sin(pi / 2)}')
print(f'cos(0) = {cos(0)}')
Solution 2: Resolve Circular Imports with Local Imports
Move the import statement inside the specific function that requires it, or refactor shared types into a standalone models.py or constants.py file.
def get_calculation():
# Local import prevents circular dependencies at module initialization time
from math import sqrt
return sqrt(144)
print(f'Calculation result: {get_calculation()}')
A common mistake is assuming that from package import subpackage works when subpackage is not imported in package/__init__.py. In Python, sub-packages are not automatically attached to parent package namespaces unless explicitly imported. Always import directly from the target module: from package.subpackage import my_function. Edge cases occur with stale .pyc bytecode files: if you renamed a function in utils.py but Python reads cached bytecode, delete __pycache__ directories to force re-compilation. Contrast this error with ModuleNotFoundError: No module named 'X', which occurs when the entire module file cannot be found on sys.path.