Python raises ImportError: cannot import name from partially initialized module error when you try to import a module or package that has not yet been fully initialized.
The main reason behind the ImportError is that if there is a circular dependency between modules, where one module tries to import another before it has finished being initialized.
Reasons for the error
- The imported class is in a circular dependency.
- The imported class is unavailable in the Python library.
- The imported class name is misspelled.
- The imported class from a module is misplaced.
- The imported class is unavailable or was not created.
Reproduce the error
# file: module_a.py
from module_b import foo
print("Module A is being initialized")
# file: module_b.py
from module_a import foo
print("Module B is being initialized")
if __name__ == "__main__":
print("Main module is being executed")
When you run the above code, you will see the below error.
Traceback (most recent call last):
File "module_a.py", line 1, in <module>
from module_b import foo
File "/path/to/module_b.py", line 1, in <module>
from module_a import foo
ImportError: cannot import name 'foo' from partially initialized module 'module_a' (most likely due to a circular import)
The error message suggests a circular dependency between the modules module_a and module_b, where each one tries to import the other before it has finished being initialized.
How to fix ImportError: cannot import ‘name’ from partially initialized ‘module’
To fix the ImportError: cannot import name from partially initialized module error, break the circular dependency by reordering your imports or using lazy imports.
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 it.
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 it is imported from the correct module.
Conclusion
Break up the circular dependency on your code or use the lazy import to fix the ImportError: cannot import name from partially initialized module error.
As a developer, we might think that all our imports should be at the top of the file, doesn’t it make your code cleaner? Yes, of course! it does make the code cleaner.