Codectionary / Developer documentation / Python

Dependency Ordering with graphlib

TopologicalSorter orders tasks so prerequisites precede dependents. The input maps each task to its predecessors, not to the tasks that depend on it. Available since Python 3.9. Run as a Python 3.11+ script.

Syntax

TopologicalSorter({task: predecessors}).static_order()

Examples

Dependency Ordering with graphlib

Run as a Python 3.11+ script.

from graphlib import TopologicalSorter
dependencies = {"compile": {"generate"}, "test": {"compile"}, "generate": set()}
order = list(TopologicalSorter(dependencies).static_order())
print(" -> ".join(order))
  1. Expected output: generate -> compile -> test
  2. This graph has one valid order because each stage depends on the previous one. Cyclic dependencies raise CycleError.

Best practices

  • Detect dependency cycles and report them to callers.
  • Do not assume a unique order among unrelated tasks.

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading