用來檢查 Python 專案是否存在循環 import。
- 不依賴專案程式碼
- 支援 AST 與 pydeps 兩種檢測方式
- 支援 function-local import 檢查
- 可輸出 Graphviz DOT dependency graph
- 可透過 CLI 或 Python API 使用
- Python 3.10 以上
REQUIREMENTS.txt內的套件
在本目錄執行:
python -m pip install -e .其他專案也可以直接指定路徑安裝:
python -m pip install -e /path/to/SMTP/tools/cycle_lint檢查目前專案:
cycle-lint --root .也可以使用 Python module 執行:
python -m cycle_lint --root .常用選項:
# 排除目錄
cycle-lint --root . --exclude tests --exclude trials
# function-local import 也視為失敗
cycle-lint --root . --fail-on-nested-imports
# 使用 pydeps 建立 dependency graph
cycle-lint --root . --engine pydeps
# 輸出 Graphviz DOT 檔案
cycle-lint --root . --dot import-graph.dotExit code:
0:檢查通過1:發現循環相依或 nested import policy violation2:設定、Python source 或檢測工具發生錯誤
from pathlib import Path
from cycle_lint.Checker import ImportCycleChecker
from cycle_lint.DataTypes import CheckerConfig
result = ImportCycleChecker(
CheckerConfig(
rootPath=Path("src"),
excludedDirectories=frozenset({"tests", "__pycache__"}),
)
).check()
if result.hasCycles:
for cycle in result.cycles:
print(" -> ".join(cycle))rootPath 必須是 Python module 的 import root。使用 src layout 時,應指定 src 目錄。
SMTP 透過 REQUIREMENTS_TEST.txt 安裝本模組,並使用以下測試確認 SMTP codebase 沒有循環相依:
python -m unittest tests.ImportCycleCheckerTest --verbose執行本模組自己的測試:
cd tools/cycle_lint
python -m unittest discover -s tests -p "*Test.py" --verbose- 只分析指定 root 內的 Python modules。
- 支援 absolute import、relative import、package initialization 與 function-local import。
- 無法可靠判斷
importlib.import_module(variable)這類動態字串 import。 - function-local import 預設只報告;加入
--fail-on-nested-imports才會使檢查失敗。