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.
Code
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
Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does this require external packages?
- Yes — `graphlib`. Add it to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.