본문 바로가기
에이전트 · 자동화원문 · prompts.chat

Python 순환 참조 감지 도구

파이썬 표준 라이브러리 ast 모듈로 프로젝트 내 순환 import를 찾고 해결 방안을 제시합니다.

원제 · Python Import Cycle Detector

추천 툴
코딩 에이전트(스킬)형식 기준 추천
쓰인 기법
에이전트 스킬(SKILL.md)

프롬프트 원문

---
name: python-import-cycle-detector
description: Finds circular imports in a Python project offline: maps files to modules, parses imports with ast, reports each cycle group with its shortest loop, exact file:line imports, import-time vs deferred vs TYPE_CHECKING, a suggested edge to break and fix patterns. Stdlib Python, self-tested.
---

# Python Import Cycle Detector

You help developers find and untangle circular imports in a Python codebase. Circular imports cause the classic `ImportError: cannot import name 'X' from partially initialized module`, `AttributeError: partially initialized module` errors that appear only in some entry points or test orders, and slow, tangled packages that are hard to split. You map the project's internal import graph, show exactly which import lines form each loop, and propose the smallest safe change that breaks it.

You work on the user's code locally and never upload it. The script only parses files with `ast`; it never imports or runs project code. You explain results in plain language and suggest refactors, but you do not rewrite large parts of the codebase without the user's go-ahead.

## Files in this skill

- `scripts/import_cycles.py` - walks the project (skips venvs, build and cache folders; detects a `src/` layout), resolves absolute and relative imports and `from pkg import submodule`, finds strongly connected components (Tarjan), the shortest cycle in each, and findings IC00-IC06; `--json` for tooling, `--include-type-checking` to count `if TYPE_CHECKING:` imports, `--root` to set the folder that holds the top-level packages, `--self-test` runs 18 checks (Python 3.8+ standard library only)
- `references/how-cycles-break.md` - why some cycles crash at import time and others do not, how Python executes a module while it is half-initialized, and what each finding means
- `references/fix-patterns.md` - seven ways to break a cycle, from moving one constant to dependency inversion, with before/after snippets and when to use each
- `templates/cycle-report.md` - the summary you hand back
- `examples/shop/` - a fictional six-module package with a real import-time cycle (`models` <-> `orders`), a longer loop through a deferred import, a `TYPE_CHECKING` import and an `__init__` re-export; `python3 -c "import shop"` inside `examples/` reproduces the ImportError

## Workflow

### 1. Understand the symptom
Ask for the exact error and traceback if there is one, the entry point or test that fails, the Python version, and where the packages live (repo root or `src/`). A cycle that only fails from one entry point usually means the import order differs between entry points.

### 2. Run the detector
```
python3 scripts/import_cycles.py path/to/project
python3 scripts/import_cycles.py path/to/project --root path/to/project/src
python3 scripts/import_cycles.py path/to/project --json > cycles.json
python3 scripts/import_cycles.py --self-test
```
Exit 0 = no import-time cycles, 1 = at least one import-time cycle (IC01), 2 = bad input. Without a shell, read the import lines at the top of the modules named in the traceback and follow them by hand until you return to the first module.

### 3. Read the report
- **Group**: modules that reach each other through imports. Fix groups one at a time, the import-time ones (IC01) first.
- **Shortest cycle**: the smallest loop with file and line for every import; usually the best place to start.
- **Kind**: `top` runs when the module is imported; `deferred` runs inside a function (IC02: works today but breaks when someone moves it to the top); `type_checking` never runs (IC06, ignored unless `--include-type-checking`).
- **Suggested place to break**: a top-level edge in the shortest cycle that imports the fewest names. It is a starting point, not a verdict: prefer the edge whose direction is "wrong" for the architecture (a low-level module such as `models` importing a high-level one such as `orders`).
- IC03 marks tangles of 5+ modules (plan a layered refactor), IC04 an `__init__.py` re-export that pulls the package into the loop, IC05 a star import inside a cycle, IC00 files that could not be parsed.

### 4. Choose a fix
Use `references/fix-patterns.md`. Default order: move the shared constant or type to a lower module; import the module instead of a name (`from shop import orders` then `orders.ORDER_STATUSES`) only as a stopgap; use a `TYPE_CHECKING` import plus string annotations for type-only use; move logic to the module that owns it; invert the dependency with a parameter, callback or registry. Avoid hiding the cycle with function-level imports unless it is a deliberate, commented exception.

### 5. Verify
Re-run the detector until the group is gone or only documented deferred edges remain, then import every top-level module in a fresh interpreter (`python3 -c "import pkg.module"`) and run the test suite. Suggest adding the detector to CI with exit code 1 failing the build.

### 6. Report
Fill `templates/cycle-report.md`: groups found, the fix for each, the changed files, and what was verified.

## Rules
- Never execute or import the user's project to analyze it; the parser is enough.
- Keep changes small and reviewable: one cycle per commit, no behavior change.
- Dynamic imports (`importlib.import_module`, plugins, `__import__`) are invisible to static analysis; say so when the project uses them.

FILE:references/how-cycles-break.md
# How circular imports break (and when they don't)

## What Python does on `import a`
1. Looks in `sys.modules`. If `a` is there, even half-finished, it returns it immediately.
2. Otherwise it creates an empty module object, puts it in `sys.modules["a"]`, and runs `a.py` from top to bottom.
3. Names exist in `a` only after the line that defines them has run.

So in a cycle `a -> b -> a`:
- `import a` starts running `a.py`, which reaches `import b`.
- `b.py` runs and reaches `import a`; `a` is already in `sys.modules` (half-initialized), so it is returned at once.
- If `b` then does `from a import X` (or uses `a.X` at top level) before `a` has defined `X`, you get
  `ImportError: cannot import name 'X' from partially initialized module 'a'` or
  `AttributeError: partially initialized module 'a' has no attribute 'X'`.

Whether it crashes depends on **which module is imported first** and **what each side touches at import time**. That is why a cycle can pass the test suite and crash in production from a different entry point.

## Kinds of edges the script reports
| kind | where the import is | runs when | risk |
|---|---|---|---|
| `top` | module level (also inside `if`, `try`, `class` bodies) | the module is imported | can crash at import time |
| `deferred` | inside a function or method | the function is called | works if the other module has finished by then; fragile |
| `type_checking` | inside `if TYPE_CHECKING:` | never at runtime | no runtime effect; ignored by default |

## Findings
| code | severity | meaning | first move |
|---|---|---|---|
| IC00 | low | a file could not be parsed (syntax error, encoding) | fix or exclude the file, re-run |
| IC01 | high | cycle made only of import-time edges somewhere in the group | fix now; see fix-patterns.md 1-5 |
| IC02 | medium | every loop includes at least one deferred import | document it or remove the cycle properly |
| IC03 | medium | group of 5+ modules | draw the intended layers; fix edges that point upward |
| IC04 | medium | an `__init__.py` re-export sits in the shortest cycle | stop re-exporting, or import submodules directly |
| IC05 | medium | `from x import *` inside a cycle | replace with explicit names |
| IC06 | info | TYPE_CHECKING-only imports were ignored | nothing; use `--include-type-checking` to see them |

## How modules are resolved
- File `pkg/sub/mod.py` under the root becomes `pkg.sub.mod`; `pkg/__init__.py` becomes `pkg`.
- The root is `<project>/src` if it exists, otherwise `<project>`; override with `--root`.
- `from pkg import name` maps to `pkg.name` when that is a module, otherwise to `pkg`.
- `from . import x` and `from ..core import y` are resolved against the importing module's package.
- Third-party and standard library imports are ignored (they are not files under the root).
- Limitation: `import a.b` also runs `a/__init__.py`; the script records only the edge to `a.b`. If a package `__init__` imports heavily, check it by hand.

## Worked example (examples/shop)
`shop.orders` line 3 imports `Customer` from `shop.models`; `shop.models` line 3 imports `ORDER_STATUSES` from `shop.orders`. Importing `shop` runs `__init__` -> `orders` -> `models`, and `models` asks for `ORDER_STATUSES` before `orders` has defined it, so `python3 -c "import shop"` fails with the ImportError. The longer loop `orders -> payments -> notifications -> orders` survives only because `notifications` imports `orders` inside `send_receipt()`.

FILE:references/fix-patterns.md
# Fix patterns for circular imports

Pick the smallest change that makes dependencies point one way: from high-level modules (services, views, CLI) down to low-level ones (models, constants, utilities).

## 1. Move the shared piece down
When two modules share a constant, enum, exception or small type, move it to a lower module that imports neither.
```python
# before: models.py -> orders.py for ORDER_STATUSES, orders.py -> models.py for Customer
# after: shop/constants.py
ORDER_STATUSES = ["new", "paid", "shipped", "cancelled"]
# models.py and orders.py both: from shop.constants import ORDER_STATUSES
```
Best first choice: no behavior change, easy to review.

## 2. Type-only imports
If one side needs the other only for annotations:
```python
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
    from shop.models import Customer
def greet(customer: Customer) -> str: ...
```
The import never runs, so the runtime cycle disappears.

## 3. Move the function to its owner
A helper in `orders.py` that only works on customers belongs in `models.py` (or a `customers.py`). Cycles often show that one function lives in the wrong module.

## 4. Dependency inversion
The low-level module should not call the high-level one. Pass what it needs instead:
```python
# payments.py
def charge(order, on_success=None):
    ...
    if on_success:
        on_success(order)
# orders.py
payments.charge(order, on_success=notifications.send_receipt)
```
Alternatives: a small registry or signal (`events.subscribe("order_paid", send_receipt)`), or a protocol/ABC in a lower module.

## 5. Split a module that does two jobs
If `utils.py` imports half the project and half the project imports `utils.py`, split it by topic (`utils/text.py`, `utils/money.py`) so each part depends on less.

## 6. Import the module, not the name (stopgap)
`from shop import orders` and use `orders.ORDER_STATUSES` inside functions. Attribute lookup happens later, so some cycles stop crashing. It hides the design problem; leave a TODO and plan pattern 1-5.

## 7. Deferred import (last resort)
```python
def send_receipt(order):
    from shop.orders import ORDER_STATUSES  # deliberate: breaks cycle orders -> payments -> notifications
```
Acceptable for rarely used paths or optional heavy dependencies. Always add a comment naming the cycle; the detector keeps reporting it as IC02.

## Package `__init__.py` re-exports (IC04)
`from .orders import Order` in `__init__.py` makes `import shop.models` run `orders.py` first. Options: keep `__init__.py` light, re-export only leaf modules, or use a lazy `__getattr__` (PEP 562) for convenience names.

## After every fix
1. `python3 scripts/import_cycles.py <project>` - the group should be gone or smaller.
2. `python3 -c "import <each top-level module>"` in a fresh interpreter.
3. Run the tests, including any that import modules in a different order.
4. Add the detector to CI: a non-zero exit fails the build.

FILE:templates/cycle-report.md
# Import cycle report - {{project}} ({{date}})

**Scope:** {{modules}} modules under `{{root}}`

출처 · prompts.chat 공개 프롬프트 모음 · 작성 Fatih Kadir Akın — CC0(저작권 포기)로 공개된 원문을 그대로 싣습니다. 한국어 제목 · 설명은 AI 번역이며, 실행 결과는 아직 없습니다.

같은 분야 프롬프트 에이전트 · 자동화

더 보기 ›