summaryrefslogtreecommitdiff
path: root/lib/sqlalchemy/util/topological.py
diff options
context:
space:
mode:
Diffstat (limited to 'lib/sqlalchemy/util/topological.py')
-rw-r--r--lib/sqlalchemy/util/topological.py35
1 files changed, 27 insertions, 8 deletions
diff --git a/lib/sqlalchemy/util/topological.py b/lib/sqlalchemy/util/topological.py
index 37297103e..24e478b57 100644
--- a/lib/sqlalchemy/util/topological.py
+++ b/lib/sqlalchemy/util/topological.py
@@ -4,21 +4,33 @@
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php
-# mypy: allow-untyped-defs, allow-untyped-calls
"""Topological sorting algorithms."""
from __future__ import annotations
+from typing import Any
+from typing import DefaultDict
+from typing import Iterable
+from typing import Iterator
+from typing import Sequence
+from typing import Set
+from typing import Tuple
+from typing import TypeVar
+
from .. import util
from ..exc import CircularDependencyError
+_T = TypeVar("_T", bound=Any)
+
__all__ = ["sort", "sort_as_subsets", "find_cycles"]
-def sort_as_subsets(tuples, allitems):
+def sort_as_subsets(
+ tuples: Iterable[Tuple[_T, _T]], allitems: Iterable[_T]
+) -> Iterator[Sequence[_T]]:
- edges = util.defaultdict(set)
+ edges: DefaultDict[_T, Set[_T]] = util.defaultdict(set)
for parent, child in tuples:
edges[child].add(parent)
@@ -43,7 +55,11 @@ def sort_as_subsets(tuples, allitems):
yield output
-def sort(tuples, allitems, deterministic_order=True):
+def sort(
+ tuples: Iterable[Tuple[_T, _T]],
+ allitems: Iterable[_T],
+ deterministic_order: bool = True,
+) -> Iterator[_T]:
"""sort the given list of items by dependency.
'tuples' is a list of tuples representing a partial ordering.
@@ -59,11 +75,14 @@ def sort(tuples, allitems, deterministic_order=True):
yield s
-def find_cycles(tuples, allitems):
+def find_cycles(
+ tuples: Iterable[Tuple[_T, _T]],
+ allitems: Iterable[_T],
+) -> Set[_T]:
# adapted from:
# https://neopythonic.blogspot.com/2009/01/detecting-cycles-in-directed-graph.html
- edges = util.defaultdict(set)
+ edges: DefaultDict[_T, Set[_T]] = util.defaultdict(set)
for parent, child in tuples:
edges[parent].add(child)
nodes_to_test = set(edges)
@@ -99,5 +118,5 @@ def find_cycles(tuples, allitems):
return output
-def _gen_edges(edges):
- return set([(right, left) for left in edges for right in edges[left]])
+def _gen_edges(edges: DefaultDict[_T, Set[_T]]) -> Set[Tuple[_T, _T]]:
+ return {(right, left) for left in edges for right in edges[left]}