Typing Stubs for toposort
types-toposort provides type hints (typing stubs) for the `toposort` Python library, which implements a topological sort algorithm for directed acyclic graphs (DAGs). This stub package, currently at version 1.10.0.20260408, is part of the `typeshed` project and is released automatically, often daily, reflecting updates to the underlying typeshed definitions for `toposort`.
Warnings
- gotcha `types-toposort` is a stub-only package. It provides type annotations but no runtime code. You must install the `toposort` package separately for the actual functionality.
- gotcha The versioning of `types-toposort` (and other typeshed stubs) is tied to typeshed's release cycle, not directly to `toposort`'s patch version. The stub's major.minor version indicates the target `toposort` version, but subsequent numbers (`.YYYYMMDD`) are typeshed internal. This can lead to minor version mismatches or breaking type checks if `toposort` introduces changes within a minor release, or if the stubs are updated more frequently.
- gotcha Topological sort algorithms are designed for Directed Acyclic Graphs (DAGs). Providing a graph that contains cycles will result in a `CycleError` at runtime from the `toposort` library, as a valid topological ordering cannot be determined.
- gotcha For Python 3.9 and newer, the standard library includes `graphlib.TopologicalSorter`, which provides similar functionality. Consider using the standard library implementation if you do not have specific needs met only by the `toposort` package.
Install
-
pip install toposort types-toposort
Imports
- toposort
from toposort import toposort
- toposort_flatten
from toposort import toposort_flatten
Quickstart
from toposort import toposort, toposort_flatten
# Example graph where keys depend on values
dependencies = {
2: {11},
9: {11, 8, 10},
10: {11, 3},
11: {7, 5},
8: {7, 3},
3: set(), # 3 has no dependencies
5: set(), # 5 has no dependencies
7: set() # 7 has no dependencies
}
# Perform a topological sort, returning sets of independent nodes at each level
layered_sort = toposort(dependencies)
print(f"Layered topological sort: {list(layered_sort)}")
# Perform a topological sort, returning a single flattened list
flattened_sort = toposort_flatten(dependencies)
print(f"Flattened topological sort: {list(flattened_sort)}")