ImportError: cannot import name 'X' from 'module' occurs when Python finds the module but cannot find the specified name inside it. This is different from ModuleNotFoundError, which occurs when Python cannot locate the module itself.
When Does This Error Occur?
Below, are the reason that's why Importerror: Cannot Import Name occurs in Python:
- Circular imports
- Importing a Non-Existing Name
- Incorrect Module Path or Package Structure
- Module Shadowing (Name Conflicts)
Circular Import
A circular import happens when two modules import each other at the top level. For example, consider two modules:
module_a.py
from module_b import function_b
def function_a():
print("Function A")
module_b.py
from module_a import function_a
def function_b():
print("Function B")
Output: Running either module may result in
Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 2, in <module>
from module_b import function_b
Importerror: No module named 'module_b'
Explanation: When module_a imports module_b, Python starts executing module_b. But module_b immediately tries to import from module_a, which is not fully initialized yet.
This error can be resolved by either of the following to ways:
1. Move Import Inside Function
# module_a.py
def function_a():
from module_b import function_b
print("Function A")
function_b()
# module_b.py
def function_b():
print("Function B")
This delays the import until runtime and avoids the circular dependency at module load time.
2. Move shared functionality into a third module: This is the cleaner architectural solution.
module_a → shared
module_b → shared
Importing a Non-Existing Name
This happens when you try to import something that the module does not define.
mymodule.py
def another_function():
print("Another Function")
main.py
# main.py
from mymodule import my_function
my_function()
Output:
Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 2, in <module>
from mymodule import my_function
Importerror: No module named 'mymodule'
This issue can be resolved by using the correct name for the function in the import statement.
Incorrect Module Path or Package Structure
Improper import paths commonly cause this error. Exanple directory structure:
project/
│
├── main.py
└── utils/
└── helper.py
Incorrect Import (in main.py)
from helper import func
Correct Import:
from utils.helper import func
If using packages, ensure:
- Proper directory structure
- Correct relative or absolute imports
- __init__.py present (for older Python versions)
Module Shadowing (Name Conflicts)
If your file name matches a standard library or installed package, Python may import the wrong module.
File name:
math.py
Code:
from math import sqrt
Python may import your local math.py instead of the built-in math module. To fix this, rename your file and remove compiled .pyc files if necessary