On this page
  1. graphlib
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Parallel Stage Execution with prepare() / get_ready() / done()
  7. 2. Detecting Cycles Explicitly (CycleError)
  8. Gotchas & Boundaries
  9. Classes & Objects

graphlib

Prev: glob | Up: stdlib_module | Next: grp
Rel: datetime, zoneinfo, calendar, collections, heapq
Ref: docs.python.org โ€” graphlib
Tags: #public #python3 #stdlib


Import

import graphlib

Overview

Topological sorting for directed acyclic graphs (TopologicalSorter, CycleError) built into Python 3.9+. Ideal for build systems, task/pipeline dependency ordering, database migration runners, and package resolution without pulling in NetworkX.

Quick Start

from graphlib import TopologicalSorter

# Key depends on values in its set (predecessors):
deps = {
    "deploy": {"build", "test"},
    "test": {"build"},
    "build": {"lint"},
    "lint": set(),
}
order = list(TopologicalSorter(deps).static_order())
assert order.index("lint") < order.index("build") < order.index("test") < order.index("deploy")

Implementation Walkthrough

1. Parallel Stage Execution with prepare() / get_ready() / done()

For parallel task runners, get_ready() returns every node whose predecessors have completed so you can schedule them concurrently:

from graphlib import TopologicalSorter

ts = TopologicalSorter({"D": {"B", "C"}, "B": {"A"}, "C": {"A"}, "A": set()})
ts.prepare()

stages: list[tuple[str, ...]] = []
while ts.is_active():
    ready = ts.get_ready()
    stages.append(ready)
    ts.done(*ready)

assert stages[0] == ("A",) and set(stages[1]) == {"B", "C"} and stages[2] == ("D",)

2. Detecting Cycles Explicitly (CycleError)

from graphlib import CycleError, TopologicalSorter

try:
    list(TopologicalSorter({"a": {"b"}, "b": {"a"}}).static_order())
except CycleError as exc:
    cycle = exc.args[1]
    assert len(cycle) >= 3

Gotchas & Boundaries

Classes & Objects

Linked from

Related notes