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