W3docs

What can I do about "ImportError: Cannot import name X" or "AttributeError: ... (most likely due to a circular import)"?

This error typically occurs when there is a circular import between two or more modules.

This error typically occurs when there is a circular import between two or more modules. A circular import occurs when module A imports module B, and module B imports module A.

A common workaround is to move the import statement inside the function that uses it (lazy import).

Here is an example:

Circular dependency example in Python

# module A
import B

# module B
import A

Instead of this, you can use

Fix the circular dependency in Python

# module A

def use_b():
    import B

# module B

def use_a():
    import A

This delays the import until the function is called. By that time, both modules have already been loaded into memory, which breaks the circular dependency at runtime. Note that these are temporary workarounds; restructuring the code to remove the circular dependency or using dependency injection is recommended for long-term stability.