python import ai_generated true

ImportError: cannot import name 'X' from partially initialized module 'Y' (most likely due to a circular import)

ID: python/importerror-circular

Also available as: JSON · Markdown
95%Fix Rate
96%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
311 active

Root Cause

Circular import detected — module A imports from B which imports from A before A is fully loaded.

generic

Workarounds

  1. 93% success Move the import inside the function that needs it (lazy import)
    def func(): from module_b import X — defers import until runtime

    Sources: https://docs.python.org/3/faq/programming.html#what-are-the-best-practices-for-using-import-in-a-package

  2. 95% success Restructure modules to extract shared code into a third module
    Create a common.py with shared definitions imported by both A and B

Dead Ends

Common approaches that don't work:

  1. Reordering imports alphabetically 85% fail

    Does not break the cycle; both modules still depend on each other

  2. Using importlib.reload() 70% fail

    Does not break circular dependency; may cause duplicate state

Error Chain

Frequently confused with: