Sub topic 14
Using Python's graphlib.TopologicalSorter
Earlier chapters built Kahn's algorithm and the DFS-based sort by hand. In production code you usually don't need to. Since Python 3.9, the standard library includes graphlib.TopologicalSorter, which implements Kahn's algorithm, detects cycles, and supports parallel execution of independent tasks.
This chapter assumes you know Python, Kahn's algorithm with in-degree counts, how cycle detection works, and the level-by-level grouping from the parallel scheduling chapter.
The Direction Convention
The class models edges the opposite way from the earlier chapters. Our hand-written functions took a graph that maps each node to the nodes that come after it (its successors). TopologicalSorter takes a mapping from each node to the nodes it depends on (its predecessors).
| Representation | `{"lib": ["utils"]}` means | Used by |
|---|---|---|
| Successor form | `lib` comes before `utils` | `topo_sort_kahn`, `topo_sort_dfs` in this tutorial |
| Predecessor form | `lib` depends on `utils`, so `utils` comes first | `graphlib.TopologicalSorter` |
The Simplest Use: static_order
static_order() returns an iterator over every node in a valid topological order:
from graphlib import TopologicalSorter, CycleError
deps = {
"app": ["lib", "config"],
"lib": ["utils"],
"config": [],
"utils": [],
}
try:
print(list(TopologicalSorter(deps).static_order()))
except CycleError as err:
print("cycle:", err.args[1])
# ['config', 'utils', 'lib', 'app']Nodes that appear only as predecessors are added automatically. You could leave out the "config": [] and "utils": [] entries and get the same result.
How the order is chosen
Internally, static_order() runs the level-by-level version of Kahn's algorithm. It collects every node whose predecessors are all finished, yields that batch, marks the whole batch done, and repeats. Within a batch, nodes come out in the order they were first added to the sorter. That is why config comes before utils in the example above.
The consequence is that the output depends on insertion order. If your dependency lists are Python sets of strings, iteration order can change between interpreter runs because of hash randomization, so the output can change too. The order is valid in every run, but different runs may produce different valid orders.
Building the Graph Incrementally with add
You don't have to build a dictionary first. add(node, *predecessors) registers a node and any number of things it depends on. Calling it again for the same node adds more dependencies.
from graphlib import TopologicalSorter
ts = TopologicalSorter()
ts.add("app", "lib", "config")
ts.add("lib", "utils")
ts.add("utils") # a node with no dependencies
print(list(ts.static_order()))
# ['config', 'utils', 'lib', 'app']add also makes it easy to convert a successor-form graph from earlier chapters without reversing it by hand. For every edge u -> v, call add(v, u), because v depends on u:
from graphlib import TopologicalSorter
courses = {
"intro": ["data_structures", "discrete_math"],
"discrete_math": ["algorithms"],
"data_structures": ["algorithms"],
"algorithms": [],
}
ts = TopologicalSorter()
for u, successors in courses.items():
ts.add(u) # keep isolated nodes
for v in successors:
ts.add(v, u) # v depends on u
print(list(ts.static_order()))
# ['intro', 'data_structures', 'discrete_math', 'algorithms']This produces the same order as topo_sort_kahn(courses) from the Kahn's algorithm chapter.
Cycle Detection with CycleError
If the dependencies contain a cycle, the sorter raises graphlib.CycleError, a subclass of ValueError. The second element of err.args is a list of nodes forming one cycle. The first and last entries are the same node, so the loop is visible.
from graphlib import TopologicalSorter, CycleError
deps = {"a": ["b"], "b": ["c"], "c": ["a"]}
try:
list(TopologicalSorter(deps).static_order())
except CycleError as err:
message, cycle = err.args
print(message)
print(" -> ".join(map(str, cycle)))
# nodes are in a cycle
# a -> c -> b -> aThe reported cycle follows successor edges ("comes before"), so a -> c means a must come before c, which is the same as saying c depends on a. Read it in reverse to get the "depends on" chain: a depends on b, b depends on c, c depends on a.
Some details matter when you report errors to users:
- The error reports one cycle, even if the graph contains several. After fixing it, run the sort again to see whether another cycle remains.
- The check runs when the graph is prepared, before any node is returned. This differs from our hand-written Kahn's algorithm, which only found the cycle after the queue ran dry.
- A self-loop, such as
ts.add("x", "x"), counts as a cycle of length one.
The Incremental API: prepare, get_ready, done
static_order() returns the nodes one at a time. A build tool or job scheduler wants something different: start every task that is currently unblocked, and release new tasks as soon as their dependencies finish. Four methods handle this:
| Method | What it does |
|---|---|
| `prepare()` | Freezes the graph and checks for cycles. Call it exactly once. |
| `get_ready()` | Returns a tuple of nodes whose predecessors are all done and that have not been returned yet. It may return an empty tuple. |
| `done(*nodes)` | Marks nodes as finished, which may unblock their dependents. |
| `is_active()` | Returns `True` while there are nodes left to return or results still pending. |
Here is a complete parallel runner built on a thread pool. Each task starts as soon as its own dependencies finish, without waiting for the rest of its level:
import time
from concurrent.futures import ThreadPoolExecutor, FIRST_COMPLETED, wait
from graphlib import TopologicalSorter
deps = {
"test": ["compile", "lint"],
"compile": ["fetch"],
"lint": ["fetch"],
"fetch": [],
}
def run(task):
time.sleep(0.1) # stand-in for real work
return task
ts = TopologicalSorter(deps)
ts.prepare() # raises CycleError here if needed
with ThreadPoolExecutor(max_workers=4) as pool:
pending = {}
while ts.is_active():
for task in ts.get_ready():
pending[pool.submit(run, task)] = task
finished, _ = wait(list(pending), return_when=FIRST_COMPLETED)
for fut in finished:
task = pending.pop(fut)
fut.result() # re-raise any exception from the task
print("done:", task)
ts.done(task)This prints done: fetch first and done: test last. compile and lint run at the same time, so they can finish in either order. The loop cannot hang. While is_active() is true, every node is either ready (and gets submitted on this pass) or already submitted, so pending is never empty when wait is called.
This approach schedules better than the fixed levels from topo_levels. With fixed levels, a slow task delays the whole next level. With get_ready and done, a node is released as soon as its own predecessors finish.
Gotchas
Methods that can only be called once
prepare()raisesValueErrorif called twice.static_order()callsprepare()internally, so you cannot callstatic_order()afterprepare(), and you cannot call either one twice on the same sorter. Create a new sorter for each run.add()afterprepare()raisesValueError. The graph is frozen once preparation starts.
Bookkeeping errors
done(node)raisesValueErrorifnodewas never returned byget_ready(), was already marked done, or was never added.- Nodes must be hashable. A list cannot be a node, but a tuple such as
("build", "x86")can. - If a task fails and you never call
doneon it, its dependents never become ready, andis_active()stays true. In the runner above,fut.result()raises the exception, which exits the loop. In your own runners, decide explicitly whether a failure stops everything or only skips the failed task's dependents.
When to Write Your Own Instead
| Need | `graphlib` | Hand-written |
|---|---|---|
| Any valid order, with cycle detection | Yes | Yes |
| Parallel execution as tasks finish | Yes, via `get_ready`/`done` | Extra work |
| Lexicographically smallest order | No guarantee | Min-heap Kahn |
| Enumerate or count all orders | No | Backtracking |
| Longest path or other DAG DP | Gives the order only | Add relaxation step |
| Remove nodes or edges mid-run | No | Possible |
| Python older than 3.9 | Not available | Works |
A common pattern is to use graphlib to get the order and then run your own dynamic programming over list(ts.static_order()), as in the longest-path chapter.
Exercise
You have a successor-form graph g = {"a": ["b"], "b": ["c"], "c": []} and run list(TopologicalSorter(g).static_order()). What does it print, and why is it wrong for your purpose?
Show answer
It prints ['c', 'b', 'a']. TopologicalSorter reads each value as the node's predecessors, so it treats "a depends on b" and "b depends on c". The result is a valid order of the reversed graph, which is your intended order a, b, c backwards. Fix it by calling ts.add(v, u) for every successor edge u -> v.
Exercise
A colleague writes ts = TopologicalSorter(deps); ts.prepare(); order = list(ts.static_order()). What happens, and how should the code change?
Show answer
staticorder() calls prepare() internally, so the second prepare call raises ValueError. Remove the explicit ts.prepare() call. If you need the cycle check to happen early, catch CycleError around staticorder() instead, or use the prepare/getready/done API without staticorder.
Exercise
In the parallel runner, suppose "compile" takes 5 seconds and "lint" takes 1 second, and a new task "docs" depends only on "lint". Compared with running fixed levels from topo_levels, when does "docs" start?
Show answer
With get_ready/done, "docs" becomes ready as soon as lint calls done, about 1 second after fetch finishes, while compile is still running. With fixed levels, "docs" sits in the same level as "test" and waits until both compile and lint finish, about 5 seconds after fetch.