graphlib TopologicalSorter Orders Dependencies

The graphlib module computes a dependency order and, with prepare plus get_ready, hands out batches of nodes that can run in parallel right now.

PythonData Integrity

Code

pythonsnippet
24 lines
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)

Inside the snippet

Repetition is confined to while sorter.is_active() — the rest of the file is straight-line. From graphlib it pulls CycleError, TopologicalSorter — the imports name exactly which library surface the snippet touches.

The file’s state is a handful of top-level bindings: build, sorter.

What to watch for

  • Dependency check: graphlib — not built-in, must be present in the project.

Using it

The demo output is labeled (static order:, parallel batch:, cycle:), so every printed line maps back to its originating operation.

Key statements

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

Interactive Tools for This Topic

FAQ

Does this require external packages?
Yes — `graphlib`. Add it to your project before running the snippet.