brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: graphlib.TopologicalSorter orders tasks by their dependencies

Scripting
~/tips/tip-python-graphlib-topological-sorter

from graphlib import TopologicalSorter

Sorts items so every one comes after the things it depends on.

The standard library can sort tasks by their dependencies. graphlib.TopologicalSorter has been there since Python 3.9 and takes a few lines.

You give it a dict where each key maps to the nodes that must come before it, and static_order() returns a valid order. This example comes from the docs:

from graphlib import TopologicalSorter

graph = {"D": {"B", "C"}, "C": {"A"}, "B": {"A"}}
print(tuple(TopologicalSorter(graph).static_order()))
# ('A', 'C', 'B', 'D')

Containers that must start in a given order or build steps with prerequisites fit this well. You can also build the graph step by step with add(node, *predecessors):

ts = TopologicalSorter()
ts.add("web", "db")
ts.add("db")
print(list(ts.static_order()))
# ['db', 'web']

For work that can run in parallel there is a second API. Call prepare(), then loop while is_active() is true: get_ready() returns the nodes whose dependencies are done, and you report each finished one with done(). With the graph above, the first batch is A, the second is B and C together, and the last is D.

Caveats: the graph must have no cycles. A graph with a depending on b and b on a raises graphlib.CycleError, and the error carries the cycle it found. When several valid orders exist, any of them may come back, so the order of independent nodes is not something to rely on.

Further reading: graphlib

More Scripting tips import difflib $r = Invoke-RestMethod https://api.github.com/repos/PowerShell/PowerShell/releases/latest import json, os, tempfile from collections import Counter import shutil All Scripting tips (10) All topics

Link