πŸ”§ Error Fixes
Β· 1 min read

Python ImportError: Cannot Import Name β€” Circular Import Fix


ImportError: cannot import name 'MyClass' from 'mymodule'

Usually caused by circular imports β€” module A imports from B, and B imports from A.

Why this happens

When Python imports a module, it executes it top-to-bottom. If module A imports from module B at the top level, and module B also imports from module A, Python encounters a partially-initialized module. The name you’re trying to import doesn’t exist yet because the module hasn’t finished loading. This creates the β€œcannot import name” error.

Fix 1: Move the import inside the function

# ❌ Top-level circular import
from module_b import helper

# βœ… Import where you need it
def my_function():
    from module_b import helper
    return helper()

Fix 2: Restructure your code

Move shared code into a third module that both can import from:

# ❌ a.py imports from b.py, b.py imports from a.py
# βœ… Move shared code to common.py

Fix 3: Check for typos

# ❌ Name doesn't exist in that module
from utils import proccess_data

# βœ… Correct spelling
from utils import process_data

Alternative solution: Use TYPE_CHECKING for type hints

If the circular import is only needed for type annotations:

from __future__ import annotations
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from module_b import MyClass  # Only imported during type checking

Prevention

  • Keep your module dependency graph acyclic β€” if you draw arrows from importer to imported, there should be no loops.
  • Use a linter like pylint or ruff with import cycle detection enabled.

Related: Python cheat sheet Β· Python complete guide Β· Pip Install Error Fix Β· Python AttributeError Fix

πŸ“˜