python import_error ai_generated true

ImportError: cannot import name 'X' from 'module'

ID: python/importerror-cannot-import-name

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
311 active

Root Cause

Circular import or name doesn't exist in module. Very common in Django/Flask projects.

generic

Workarounds

  1. 90% success Use lazy import inside function to break circular dependency
    def func():
        from module import name

    Sources: https://docs.python.org/3/reference/import.html

  2. 88% success Restructure modules to eliminate circular dependency
    # Move shared definitions into a separate module:
    # common.py: shared classes/functions
    # a.py: from common import X
    # b.py: from common import X
    # This breaks the A->B->A circular chain

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

Dead Ends

Common approaches that don't work:

  1. Move import to top of file 60% fail

    May worsen circular import

  2. Rename conflicting module 50% fail

    Doesn't fix the circular dependency

Error Chain

Frequently confused with: