The Python ImportError: cannot import name
error occurs when an imported class is not accessible or is in a circular dependency.
What Causes ImportError: Cannot Import Name
This error generally occurs when a class cannot be imported due to one of the following reasons:
- The imported class is in a circular dependency.
- The imported class is unavailable or was not created.
- The imported class name is misspelled.
- The imported class from a module is misplaced.
- The imported class is unavailable in the Python library.
Python ImportError: Cannot Import Name Example
Here’s an example of a Python ImportError: cannot import name
thrown due to a circular dependency. Two python modules
test1.py
and test2.py
are created to achieve this:
test1.py:
from test2 import Class2
class Class1:
obj = Class2()
test2.py:
from test1 import Class1
class Class2:
obj = Class1()
In the above example, the initialization of obj
in test1
depends on test2
, and obj
in test2
depends on test1
. This is a circular dependency since both files attempt to load each other. Therefore, running test1.py
(or test2.py
) causes an ImportError: cannot import name
error:
Traceback (most recent call last):
File "test1.py", line 1, in
from test2 import Class2
File "test2.py", line 1, in
from test1 import Class1
File "test1.py", line 1, in
from test2 import Class2
ImportError: cannot import name 'Class2' from partially initialized module 'test2' (most likely due to a circular import) (test2.py)
How to Fix ImportError: Cannot Import Name in Python
The ImportError: cannot import name
can be fixed using the following approaches, depending on the cause of the error:
- If the error occurs due to a circular dependency, it can be resolved by moving the imported classes to a third file and importing them from this file.
- If the error occurs due to a misspelled name, the name of the class in the Python file should be verified and corrected.
- If the imported class is unavailable or not created, the file should be checked to ensure that the imported class exists in the file. If not, it should be created.
- If the imported class from a module is misplaced, it should be ensured that the class is imported from the correct module.
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!