Python Glossary Русский

Python 3.9+graphlibterm

graphlib

module

Topological sorting of a dependency graph: the order in which to run tasks so that each comes after its prerequisites.

Syntax

from graphlib import TopologicalSorter

graphlib holds a single class, TopologicalSorter, and solves one problem: ordering nodes by dependencies, such as builds, migrations or install order. It has no shortest paths or graph traversals; those are written by hand or taken from third-party libraries. The graph is a dict of "node -> its predecessors", not successors, and mixing up the direction reverses the order; a cycle raises CycleError.

Examples

from graphlib import TopologicalSorter
deps = {'app': {'db', 'cache'}, 'db': {'config'}, 'cache': {'config'}}
order = list(TopologicalSorter(deps).static_order())
print(order[0], order[-1])  # → config app

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy