---
source: https://iinventedlight.com/library/notes/python-graphlib.md
title: "Python graphlib TopologicalSorter: order tasks and detect cycles"
license: CC-BY-4.0
license_url: https://creativecommons.org/licenses/by/4.0/
source_license: "PSF-2.0 (Python docs); PSF-2.0 (python/cpython (GitHub)); prose restates cited source lines in own words"
license_family: mixed-green
attribution: "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."
author: "iinventedlight (synthesis of cited sources); text drafted with AI assistance"
date: 2026-11-18
status: published
approved_by: "Cole Withington, 2026-11-20 13:14 PT: \"Publish the full batch and rewrite the 6 live notes\""
checked_on: 2026-11-18
as_of: 2026-11-18
confidence: medium
untested: "Not reproduced (2026-11-18). Official docs and source files were read; no test suite, server, or API call was run for this note."
category: coding-references
topic_area: "code-python: graphlib"
tags: [python, graphlib, topological-sort, dependencies, dag, stdlib]
client: Librarian
sources:
  - id: S1
    title: "graphlib - Functionality to operate with graph-like structures"
    publisher: Python docs
    url: https://docs.python.org/3/library/graphlib.html
    accessed: 2026-11-18
    license: "PSF-2.0"
  - id: S2
    title: "Lib/graphlib.py"
    publisher: python/cpython (GitHub)
    url: https://github.com/python/cpython/blob/main/Lib/graphlib.py
    accessed: 2026-11-18
    license: "PSF-2.0"
---
# 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

```python
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 `graph` argument 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

1. Create a `TopologicalSorter` and add nodes.
2. Call `prepare()` to mark the graph finished and check for cycles.
3. While `is_active()` is True, process the nodes from `get_ready()`.
4. Call `done(node)` as each node finishes, which can release new ready nodes.

## Rules

- `add()` raises `ValueError` after `prepare()`.
- `prepare()` raises `CycleError` on a cycle, but `get_ready()` can still return nodes until the cycle blocks progress.
- All nodes must be hashable.

## See also

- [python-collections-containers](https://iinventedlight.com/library/notes/python-collections-containers/)
- [python-itertools](https://iinventedlight.com/library/notes/python-itertools/)

## 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.

---

Agents: [/agents.md](/agents.md) | [/.well-known/agent-library.json](/.well-known/agent-library.json).
