The `toposort` library provides a pure Python implementation of a topological sort algorithm, useful for ordering items based on their dependencies. As of its latest version `1.10`, released on February 25, 2023, it is a stable, production-ready tool. It accepts dependency graphs as dictionaries and efficiently computes a valid processing order. The release cadence appears to be moderate, with updates for compatibility and minor enhancements.
pip install toposortVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to use `toposort` with a sample dependency graph. The `data` dictionary maps each dependent node to a set of its direct dependencies. `toposort` yields sets of nodes that can be processed concurrently, while `toposort_flatten` provides a single linear sequence. It also shows how to catch `CircularDependencyError` for graphs containing cycles.
Ensure your dependency graph is a Directed Acyclic Graph (DAG). If cycles are expected or possible, implement logic to detect and handle `CircularDependencyError`.
Always provide dependencies as `set`s (`{dependency1, dependency2}`) and ensure the mapping is `dependent_node: {its_dependencies}`.Represent your graph nodes using hashable Python types. If you need to use complex objects, consider using a unique identifier (like an ID string or number) as the node in the topological sort, and map it back to your complex object.
Evaluate `graphlib.TopologicalSorter` from the Python standard library as an alternative, especially for new projects or to reduce third-party dependencies. The API differs, so code migration would be required.
Import `CircularDependencyError` directly from the `toposort` package alongside the `toposort` function: `from toposort import toposort, CircularDependencyError`. Then, catch it as `except CircularDependencyError as e:`.
No dependency data recorded yet.