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
pylintorruffwith import cycle detection enabled.
Related: Python cheat sheet Β· Python complete guide Β· Pip Install Error Fix Β· Python AttributeError Fix