Sub topic 14
Using Python's graphlib.TopologicalSorter
This chapter assumes you know Kahn's algorithm, can read Python dictionaries and sets, and have seen how a cycle stops a topological sort. Since Python 3.9, the standard library module graphlib provides TopologicalSorter. It is a ready-made implementation of Kahn's algorithm with cycle detection built in. It also has an incremental interface for running tasks in parallel.
The Direction Gotcha
The earlier chapters stored the graph as a map from each node to its successors: u -> [v] meant "u comes before v". TopologicalSorter uses the opposite direction. It maps each node to its predecessors, which are the nodes it depends on. If you pass a successor map without converting it, you get the reverse of the order you wanted, and Python raises no error.
| Representation | `{"a": {"b"}}` means | Used by |
|---|---|---|
| Successor map | a comes before b | Kahn's and DFS code in this tutorial |
| Predecessor map | a depends on b, so b comes first | `graphlib.TopologicalSorter` |
One-Shot Ordering with static_order
from graphlib import TopologicalSorter, CycleError
# Each key maps to the set of nodes it depends on (its predecessors).
deps = {
"app": {"lib", "config"},
"lib": {"utils"},
"config": set(),
"utils": set(),
}
try:
print(list(TopologicalSorter(deps).static_order()))
except CycleError as err:
print("cycle:", err.args[1])One possible output is ['config', 'utils', 'lib', 'app']. Sets have no guaranteed iteration order, so the exact order can vary. If your tests compare against a fixed list, they should check that the result is a valid order rather than one particular order.
When the dependencies contain a cycle, the sorter raises CycleError. Its args[1] holds the nodes along the cycle, with the first node repeated at the end:
from graphlib import TopologicalSorter, CycleError
try:
list(TopologicalSorter({"a": {"b"}, "b": {"a"}}).static_order())
except CycleError as err:
print("cycle:", err.args[1])
# cycle: ['a', 'b', 'a'] (the starting node may differ)The Incremental Interface
For parallel scheduling, build the sorter with add(node, *predecessors). Then call prepare() once and work through a loop. get_ready() returns every node whose dependencies are all finished, and done() marks nodes as complete.
from graphlib import TopologicalSorter
ts = TopologicalSorter()
ts.add("compile", "fetch")
ts.add("lint", "fetch")
ts.add("test", "compile", "lint")
ts.prepare()
while ts.is_active():
ready = ts.get_ready()
print(sorted(ready))
ts.done(*ready)
# ['fetch']
# ['compile', 'lint']
# ['test']When you call done() on every batch together like this, the batches are the parallel levels from the earlier chapter. In a real scheduler, you would send the ready nodes to worker threads and call done(node) as each one finishes. Any newly unblocked nodes appear on the next get_ready() call.
Converting a Successor Map
If your data is in the successor form used earlier in this tutorial, reverse each edge as you add it:
from graphlib import TopologicalSorter
succ = {"intro": ["dsa", "math"], "dsa": ["algo"], "math": ["algo"], "algo": []}
ts = TopologicalSorter()
for u, vs in succ.items():
ts.add(u) # keeps nodes that have no edges
for v in vs:
ts.add(v, u) # v depends on u
print(list(ts.static_order()))Exercise
You pass the successor map {"fetch": {"build"}, "build": {"deploy"}, "deploy": set()} directly to TopologicalSorter and call static_order(). What order do you get, and why is it wrong?
Show answer
You get ['deploy', 'build', 'fetch']. TopologicalSorter reads each value as the set of predecessors, so it treats fetch as depending on build and build as depending on deploy. That reverses every edge, and the result is the reverse of the intended order fetch, build, deploy.
Exercise
In the incremental loop, a worker finishes "compile" but "lint" is still running. What does the next get_ready() return, and why?
Show answer
It returns an empty tuple. "test" depends on both "compile" and "lint", so it becomes ready only after done("lint") is also called.