# pydoc > graphlib

---
type: CommandReference
command: graphlib
mode: pydoc
section: ''
source: pydoc3
---

## Quick Reference
- `import graphlib` — import the module
- `ts = TopologicalSorter(graph)` — create a sorter with initial graph
- `ts.add(node, *predecessors)` — add node and its dependencies
- `ts.prepare()` — finalize graph, detect cycles
- `ts.get_ready()` — get tuple of nodes ready for processing
- `ts.done(*nodes)` — mark nodes as processed
- `ts.is_active()` — check if more progress possible
- `ts.static_order()` — iterate nodes in topological order
- `graphlib.CycleError` — exception raised when cycles exist

## Name
graphlib — functionality to topologically sort a graph of hashable nodes

## Synopsis
python
import graphlib

# Create a topological sorter
ts = graphlib.TopologicalSorter()

# Add nodes and dependencies
ts.add('A', 'B', 'C')  # A depends on B and C
ts.add('B', 'D')       # B depends on D
ts.add('C', 'D')       # C depends on D
ts.add('D')            # D has no dependencies

# Prepare the graph (detects cycles)
ts.prepare()

# Process nodes in order
while ts.is_active():
    ready = ts.get_ready()
    # ... process each node in ready ...
    ts.done(*ready)
## Methods

### `TopologicalSorter.__init__(self, graph=None)`
Initialize the sorter. If `graph` is provided, it must be a mapping from nodes to iterables of predecessors. Default is an empty graph.

### `TopologicalSorter.add(self, node, *predecessors)`
Add a new node and its predecessors to the graph. Both `node` and all elements in `predecessors` must be hashable. If called multiple times with the same node, the set of dependencies is the union. Raises `ValueError` if called after `prepare()`.

### `TopologicalSorter.prepare(self)`
Mark the graph as finished and check for cycles. If a cycle is detected, `CycleError` is raised. After this call, the graph cannot be modified.

### `TopologicalSorter.get_ready(self)`
Return a tuple of all nodes that are ready (all predecessors processed). Initially returns nodes with no predecessors. After calling `done()`, returns new nodes whose predecessors are all processed. Raises `ValueError` if `prepare()` was not called.

### `TopologicalSorter.done(self, *nodes)`
Mark a set of nodes (returned by `get_ready()`) as processed. Unblocks their successors. Raises `ValueError` if any node was already marked done, was not added to the graph, or was not yet returned by `get_ready()`.

### `TopologicalSorter.is_active(self)`
Return `True` if more progress can be made (nodes ready or pending), `False` otherwise. Raises `ValueError` if `prepare()` was not called.

### `TopologicalSorter.static_order(self)`
Return an iterable of nodes in a topological order. Does not require calling `prepare()` or `done()`. Raises `CycleError` if a cycle is detected.

### `TopologicalSorter.__bool__(self)`
Return `True` if the graph has nodes that can be processed. (Implementation detail; used for truthiness.)

## Exceptions

### `CycleError`
Subclass of `ValueError`. Raised by `TopologicalSorter.prepare()` or `static_order()` if cycles exist in the graph. The detected cycle can be accessed via the second element in the `args` attribute of the exception instance: a list of nodes where the first and last node are the same.

## Examples

python
import graphlib

# Example: course prerequisites
courses = {
    'Math101': (),
    'Math201': ('Math101',),
    'CS101': ('Math101',),
    'CS201': ('CS101', 'Math201'),
    'CS301': ('CS201',)
}

ts = graphlib.TopologicalSorter(courses)
ts.prepare()
order = list(ts.static_order())
print(order)  # e.g., ['Math101', 'CS101', 'Math201', 'CS201', 'CS301']
## See Also
- [Python graphlib documentation](https://docs.python.org/3.10/library/graphlib.html)
- `toposort` package on PyPI (alternative implementation)

## Exit Codes
Not applicable.