Elffuss BraidHub

kikocis/llama-stack public

main · 2.7 KiBRawPermalink
1# Copyright (c) Meta Platforms, Inc. and affiliates.
2# All rights reserved.
3#
4# This source code is licensed under the terms described in the LICENSE file in
5# the root directory of this source tree.
6
7"""
8Type-safe data interchange for Python data classes.
9
10:see: https://github.com/hunyadi/strong_typing
11"""
12
13from typing import Callable, Dict, Iterable, List, Optional, Set, TypeVar
14
15from .inspection import TypeCollector
16
17T = TypeVar("T")
18
19
20def topological_sort(graph: Dict[T, Set[T]]) -> List[T]:
21 """
22 Performs a topological sort of a graph.
23
24 Nodes with no outgoing edges are first. Nodes with no incoming edges are last.
25 The topological ordering is not unique.
26
27 :param graph: A dictionary of mappings from nodes to adjacent nodes. Keys and set members must be hashable.
28 :returns: The list of nodes in topological order.
29 """
30
31 # empty list that will contain the sorted nodes (in reverse order)
32 ordered: List[T] = []
33
34 seen: Dict[T, bool] = {}
35
36 def _visit(n: T) -> None:
37 status = seen.get(n)
38 if status is not None:
39 if status: # node has a permanent mark
40 return
41 else: # node has a temporary mark
42 raise RuntimeError(f"cycle detected in graph for node {n}")
43
44 seen[n] = False # apply temporary mark
45 for m in graph[n]: # visit all adjacent nodes
46 if m != n: # ignore self-referencing nodes
47 _visit(m)
48
49 seen[n] = True # apply permanent mark
50 ordered.append(n)
51
52 for n in graph.keys():
53 _visit(n)
54
55 return ordered
56
57
58def type_topological_sort(
59 types: Iterable[type],
60 dependency_fn: Optional[Callable[[type], Iterable[type]]] = None,
61) -> List[type]:
62 """
63 Performs a topological sort of a list of types.
64
65 Types that don't depend on other types (i.e. fundamental types) are first. Types on which no other types depend
66 are last. The topological ordering is not unique.
67
68 :param types: A list of types (simple or composite).
69 :param dependency_fn: Returns a list of additional dependencies for a class (e.g. classes referenced by a foreign key).
70 :returns: The list of types in topological order.
71 """
72
73 if not all(isinstance(typ, type) for typ in types):
74 raise TypeError("expected a list of types")
75
76 collector = TypeCollector()
77 collector.traverse_all(types)
78 graph = collector.graph
79
80 if dependency_fn:
81 new_types: Set[type] = set()
82 for source_type, references in graph.items():
83 dependent_types = dependency_fn(source_type)
84 references.update(dependent_types)
85 new_types.update(dependent_types)
86 for new_type in new_types:
87 graph[new_type] = set()
88
89 return topological_sort(graph)