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. This error occurs when an imported class is inaccessible or in a circular dependency.

Reasons for the error

  1. The imported class is in a circular dependency.
  2. The imported class is unavailable in the Python library.
  3. The imported class name is misspelled.
  4. The imported class from a module is misplaced.
  5. The imported class is unavailable or was not created.

Flowchart

Flowchart of How to Fix ImportError: cannot import 'name' from partially initialized 'module'

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 it?

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.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.