On this page
graphlib
Prev: glob | Up: stdlib_module | Next: grp
Rel: datetime, zoneinfo, calendar, collections, heapq
Ref: docs.python.org โ graphlib
Tags: #public #python3 #stdlib
Import
import graphlib
Overview
Topological sorting for directed acyclic graphs (TopologicalSorter, CycleError) built into Python 3.9+. Ideal for build systems, task/pipeline dependency ordering, database migration runners, and package resolution without pulling in NetworkX.
Quick Start
from graphlib import TopologicalSorter
# Key depends on values in its set (predecessors):
deps = {
"deploy": {"build", "test"},
"test": {"build"},
"build": {"lint"},
"lint": set(),
}
order = list(TopologicalSorter(deps).static_order())
assert order.index("lint") < order.index("build") < order.index("test") < order.index("deploy")
Implementation Walkthrough
1. Parallel Stage Execution with prepare() / get_ready() / done()
For parallel task runners, get_ready() returns every node whose predecessors have completed so you can schedule them concurrently:
from graphlib import TopologicalSorter
ts = TopologicalSorter({"D": {"B", "C"}, "B": {"A"}, "C": {"A"}, "A": set()})
ts.prepare()
stages: list[tuple[str, ...]] = []
while ts.is_active():
ready = ts.get_ready()
stages.append(ready)
ts.done(*ready)
assert stages[0] == ("A",) and set(stages[1]) == {"B", "C"} and stages[2] == ("D",)
2. Detecting Cycles Explicitly (CycleError)
from graphlib import CycleError, TopologicalSorter
try:
list(TopologicalSorter({"a": {"b"}, "b": {"a"}}).static_order())
except CycleError as exc:
cycle = exc.args[1]
assert len(cycle) >= 3
Gotchas & Boundaries
- Edge direction is
node -> predecessors:{"B": {"A"}}meansAmust run beforeB, not the reverse. - Don't call
add()afterprepare(): Graph structure is frozen onceprepare()runs. static_order()order among independent nodes is arbitrary: Sortget_ready()batches if you need deterministic tie-breaking.
Classes & Objects
- graphlib.CycleError โ Subclass of ValueError raised by TopologicalSorter.prepare if cycles exist in the working graph. (Methods:
.add_note(),.with_traceback()) - graphlib.TopologicalSorter โ Provides functionality to topologically sort a graph of hashable nodes (Methods:
.add(),.done(),.get_ready(),.is_active(),.prepare(),.static_order())
Linked from
Related notes
- tuts/python3/stdlib_module/glob Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/graphlib/CycleError Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/graphlib/TopologicalSorter Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/grp Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/calendar Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/collections Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/datetime Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/heapq Linked here; shared tags: #stdlib