Topologically Sort Build Targets with Cycle Detection

Order build targets from a prerequisite graph with Kahn's algorithm and fail loudly when a dependency cycle prevents a complete order.

PythonCli Tooling

Code

pythonsnippet
50 lines
from __future__ import annotations

from collections import defaultdict, deque


def build_order(prerequisites: dict[str, list[str]]) -> list[str]:
    indegree = {node: 0 for node in prerequisites}
    dependents: dict[str, list[str]] = defaultdict(list)
    for node, deps in prerequisites.items():
        for dep in deps:
            indegree.setdefault(dep, 0)
            dependents[dep].append(node)
            indegree[node] += 1

    ready = deque(sorted(node for node, degree in indegree.items() if degree == 0))
    order: list[str] = []
    while ready:
        node = ready.popleft()
        order.append(node)
        for child in sorted(dependents[node]):
            indegree[child] -= 1
            if indegree[child] == 0:
                ready.append(child)

    if len(order) != len(indegree):
        blocked = sorted(node for node, degree in indegree.items() if degree > 0)
        raise ValueError(f"dependency cycle among: {', '.join(blocked)}")
    return order


def main() -> None:
    graph = {
        "app": ["api", "db"],
        "api": ["db", "auth"],
        "auth": ["db"],
        "db": [],
        "docs": [],
    }
    order = build_order(graph)
    print(" -> ".join(order))
    assert order.index("db") < order.index("api") < order.index("app")
    try:
        build_order({"a": ["b"], "b": ["a"]})
    except ValueError as exc:
        print(f"cycle: {exc}")


if __name__ == "__main__":
    main()

What the code does

Topologically Sort Build Targets with Cycle Detection is built around the functions build_order and main.

Iteration happens inside for node, deps in prerequisites.items() — everything outside it runs once. From __future__ it pulls annotations, defaultdict, deque — the imports name exactly which library surface the snippet touches. The failure path is explicit — ValueError is raised when the guard condition holds.

Points of care

  • Plan for an install step: __future__ is a real dependency, resolved by the package manager.

Applying it

The main signature reads def build_order(prerequisites: dict[str, list[str]]) -> list[str]

Output lines are prefixed (->, cycle:), making each step’s effect easy to spot.

The demo flow inside main is build_order — run the file to see it end to end.

Statements that matter

def main() -> None:
    graph = {
        "app": ["api", "db"],
        "api": ["db", "auth"],
        "auth": ["db"],
        "db": [],
        "docs": [],
    }
    order = build_order(graph)
    print(" -> ".join(order))
    assert order.index("db") < order.index("api") < order.index("app")
    try:
raise ValueError(f"dependency cycle among: {', '.join(blocked)}")
return order
def main() -> None:
graph = {
"app": ["api", "db"],
"api": ["db", "auth"],
"auth": ["db"],
"db": [],
"docs": [],
}
except ValueError as exc:
    print(f"cycle: {exc}")

Interactive Tools for This Topic

FAQ

What does the snippet do with malformed data?
It throws `ValueError` before any real work runs — handle it at the call site or let it propagate deliberately.
What does this need from the package registry?
These are real dependencies: `__future__`. Without it the snippet will not load.