Python graphlib TopologicalSorter: order tasks and detect cycles
Answer: Use TopologicalSorter.static_order() when you need an immediate sorting of the nodes in the graph and no parallelism. TopologicalSorter provides functionality to topologically sort a graph of hashable nodes. Its prepare() method raises CycleError (a subclass of ValueError) if cycles exist.
Examples
from graphlib import TopologicalSorter, CycleError
graph = {"D": {"B", "C"}, "C": {"A"}, "B": {"A"}}
ts = TopologicalSorter(graph)
tuple(ts.static_order()) # ('A', 'C', 'B', 'D')
# Parallel processing as nodes become ready
ts = TopologicalSorter()
ts.add("build", "fetch", "configure")
ts.add("test", "build")
ts.prepare()
while ts.is_active():
for node in ts.get_ready():
print("run", node)
ts.done(node)
try:
TopologicalSorter({"a": {"b"}, "b": {"a"}}).prepare()
except CycleError as err:
print("cycle:", err.args[1])
How it works
- In a topological order, for every directed edge u -> v, vertex u comes before vertex v.
- A complete ordering is possible if and only if the graph has no directed cycles.
- The optional
graphargument is a dictionary: each key is a node, and each value is an iterable of that node's predecessors. add(node, *predecessors)adds a node; calling it again for the same node unions the dependencies. Unknown predecessors are added automatically.
The parallel API
- Create a
TopologicalSorterand add nodes. - Call
prepare()to mark the graph finished and check for cycles. - While
is_active()is True, process the nodes fromget_ready(). - Call
done(node)as each node finishes, which can release new ready nodes.
Rules
add()raisesValueErrorafterprepare().prepare()raisesCycleErroron a cycle, butget_ready()can still return nodes until the cycle blocks progress.- All nodes must be hashable.
See also
Claims
- id: C1 claim: A complete ordering needs a graph with no directed cycles. source: S1 evidence: "topological ordering is possible if and only if the graph has no directed cycles"
- id: C2 claim: add raises ValueError after prepare. source: S1 evidence: "Raises ValueError if called after prepare() ."
- id: C3 claim: CycleError subclasses ValueError. source: S2 evidence: "Subclass of ValueError raised by TopologicalSorter.prepare if cycles"
- id: C4 claim: TopologicalSorter sorts a graph of hashable nodes. source: S2 evidence: "Provides functionality to topologically sort a graph of hashable nodes"
Sources
- [S1] graphlib - Functionality to operate with graph-like structures. Python docs. https://docs.python.org/3/library/graphlib.html . License: PSF-2.0. Accessed 2026-11-18.
- [S2] Lib/graphlib.py. python/cpython (GitHub). https://github.com/python/cpython/blob/main/Lib/graphlib.py . License: PSF-2.0. Accessed 2026-11-18.
License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: Python docs, graphlib - Functionality to operate with graph-like structures; python/cpython (GitHub), Lib/graphlib.py. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation. Text was condensed and changed from the originals.
License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Python docs, graphlib - Functionality to operate with graph-like structures; python/cpython (GitHub), Lib/graphlib.py. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation.
Cite this
iinventedlight. 2026. "Python graphlib TopologicalSorter: order tasks and detect cycles." iinventedlight Library, iil:note:z3hacdhx, version of 2026-11-18. https://iinventedlight.com/library/notes/python-graphlib/. License: CC-BY-4.0.
@misc{iil_note_z3hacdhx,
author = {{iinventedlight}},
title = {{Python graphlib TopologicalSorter: order tasks and detect cycles}},
howpublished = {iinventedlight Library},
year = {2026},
date = {2026-11-18},
url = {https://iinventedlight.com/library/notes/python-graphlib/},
note = {Permanent ID iil:note:z3hacdhx. License: CC-BY-4.0.},
}
Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).
Extra files beside this note
These files use this note's license, shown below. Paper extras retain their reproduction status; a link is not a reproduction.
- python-graphlib.table.json (table; CC-BY-4.0)
- python-graphlib.schema.json (schema; CC-BY-4.0)
For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/python-graphlib.md.