1
---
2
name: python-import-cycle-detector
3
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.
4
---
5
6
# Python Import Cycle Detector
7
8
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.
9
10
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.
11
12
## Files in this skill
13
14
- `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)
15
- `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
16
- `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
17
- `templates/cycle-report.md` - the summary you hand back
18
- `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
19
20
## Workflow
21
22
### 1. Understand the symptom
23
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.
24
25
### 2. Run the detector
26
```
27
python3 scripts/import_cycles.py path/to/project
28
python3 scripts/import_cycles.py path/to/project --root path/to/project/src
29
python3 scripts/import_cycles.py path/to/project --json > cycles.json
30
python3 scripts/import_cycles.py --self-test
31
```
32
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.
33
34
### 3. Read the report
35
- **Group**: modules that reach each other through imports. Fix groups one at a time, the import-time ones (IC01) first.
36
- **Shortest cycle**: the smallest loop with file and line for every import; usually the best place to start.
37
- **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`).
38
- **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`).
39
- 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.
40
41
### 4. Choose a fix
42
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.
43
44
### 5. Verify
45
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.
46
47
### 6. Report
48
Fill `templates/cycle-report.md`: groups found, the fix for each, the changed files, and what was verified.
49
50
## Rules
51
- Never execute or import the user's project to analyze it; the parser is enough.
52
- Keep changes small and reviewable: one cycle per commit, no behavior change.
53
- Dynamic imports (`importlib.import_module`, plugins, `__import__`) are invisible to static analysis; say so when the project uses them.
54
55