A circular import occurs when module A imports from module B, and module B also imports from module A. When Python first loads A, it starts loading B, which tries to import from A before A has finished initializing, resulting in an ImportError or partially initialized module.
Why it happens
- •Two modules that depend on each other import each other at the module level.
- •A utilities module imports from a models module that imports from utilities.
- •Shared constants or helpers placed in a module that also imports domain logic.
- •Frameworks with plugin systems where plugins import from the core and the core imports plugins.
Examples
Code that triggers the error
# a.py
from b import greet
def name():
return "Alice"
# b.py
from a import name
def greet():
return f"Hello {name()}"Error output
ImportError: cannot import name 'greet' from partially initialized module 'b' (most likely due to a circular import)
How to fix it
Break the cycle by moving shared code into a third module that neither A nor B imports from. Use local (function-level) imports to defer loading until the functions are called. Restructure your package so dependencies flow in one direction.
Fixed code
# a.py - no import from b at top level
def name():
return "Alice"
# b.py
def greet():
from a import name # local import breaks the cycle
return f"Hello {name()}"Related errors
Ready to practice your English at work?
Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.
Try Lingua-e for free