Scenario beginner

Debugging a Circular Import Error

Diagnose and fix a Python ImportError caused by circular imports between modules, using module restructuring, lazy imports, and TYPE_CHECKING guards.

1 min read ~10 min to complete
Steps
1 Services Used
~10 min Duration
Beginner Difficulty
The Situation

Senior Python developer / backend engineering interviews

Context: Your Python application raises ImportError: cannot import name 'UserService' from partially initialized module 'app.services' at startup. How do you diagnose and fix it?

# The circular import:
# app/models.py imports from app/services.py
# app/services.py imports from app/models.py

# models.py
from app.services import UserService   # Imports services
class User:
    ...

# services.py
from app.models import User            # Imports models → circular!
class UserService:
    def create(self, name): return User(name=name)
# Fix 1 — Restructure: move shared types to a separate module
# app/types.py (no imports from models or services)
from dataclasses import dataclass

@dataclass
class UserDTO:
    name: str
    email: str

# models.py — imports from types only
from app.types import UserDTO

# services.py — imports from types only
from app.types import UserDTO

# Fix 2 — Lazy import (defer import to function level)
# services.py
class UserService:
    def create(self, name: str):
        from app.models import User   # Import at function call time, not module load
        return User(name=name)

# Fix 3 — Use TYPE_CHECKING guard (for type hints only)
from __future__ import annotations
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from app.models import User   # Only used for type checking, not at runtime
Services Used
Python
Prerequisites
  • Python 3.10+
  • Basic OOP concepts
What You Learned
  • Why circular imports happen
  • Restructuring shared types
  • Lazy imports and TYPE_CHECKING guards

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form