← 中文资源

简体中文版本

graphlib TopologicalSorter 排布依赖顺序

graphlib 一次给出依赖顺序;prepare 配 get_ready/done 按批次发放当前可并行执行的节点,循环依赖在 prepare 时直接抛 CycleError。

阅读英文原文

实现说明

文件的主干是一个循环——while sorter.is_active()。从 graphlib 导入了 CycleError、TopologicalSorter——导入清单就是这段代码触碰的库表面。 顶层就这几处状态:build、sorter。

使用要点

  • graphlib 必须先装好——示例直接导入它们。
  • 直接运行文件,输出会带上标签,比如 static order:、parallel batch:、cycle:——输出的每一行都能指回产生它的那次调用。

常见问题

需要安装第三方包吗?

需要——graphlib。运行前请先加入项目依赖。

核心语句

except CycleError as exc:
    print("cycle:", exc)

代码示例

from graphlib import CycleError, TopologicalSorter

build = {
    "checkout": set(),
    "install": {"checkout"},
    "lint": {"install"},
    "test": {"install"},
    "bundle": {"install"},
}

print("static order:", " -> ".join(TopologicalSorter(build).static_order()))

# prepare/get_ready/done: each round hands out the batch of nodes with no unfinished dependencies (runnable in parallel)
sorter = TopologicalSorter(build)
sorter.prepare()
while sorter.is_active():
    batch = sorted(sorter.get_ready())
    print("parallel batch:", batch)
    sorter.done(*batch)

try:
    TopologicalSorter({"a": {"b"}, "b": {"a"}}).prepare()
except CycleError as exc:
    print("cycle:", exc)