Elffuss BraidHub

kikocis/llama-stack public

main · 5.8 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
13import dataclasses
14import sys
15from dataclasses import is_dataclass
16from typing import Callable, Dict, Optional, overload, Type, TypeVar, Union
17
18if sys.version_info >= (3, 9):
19 from typing import Annotated as Annotated
20else:
21 from typing_extensions import Annotated as Annotated
22
23if sys.version_info >= (3, 10):
24 from typing import TypeAlias as TypeAlias
25else:
26 from typing_extensions import TypeAlias as TypeAlias
27
28if sys.version_info >= (3, 11):
29 from typing import dataclass_transform as dataclass_transform
30else:
31 from typing_extensions import dataclass_transform as dataclass_transform
32
33T = TypeVar("T")
34
35
36def _compact_dataclass_repr(obj: object) -> str:
37 """
38 Compact data-class representation where positional arguments are used instead of keyword arguments.
39
40 :param obj: A data-class object.
41 :returns: A string that matches the pattern `Class(arg1, arg2, ...)`.
42 """
43
44 if is_dataclass(obj):
45 arglist = ", ".join(
46 repr(getattr(obj, field.name)) for field in dataclasses.fields(obj)
47 )
48 return f"{obj.__class__.__name__}({arglist})"
49 else:
50 return obj.__class__.__name__
51
52
53class CompactDataClass:
54 "A data class whose repr() uses positional rather than keyword arguments."
55
56 def __repr__(self) -> str:
57 return _compact_dataclass_repr(self)
58
59
60@overload
61def typeannotation(cls: Type[T], /) -> Type[T]: ...
62
63
64@overload
65def typeannotation(
66 cls: None, *, eq: bool = True, order: bool = False
67) -> Callable[[Type[T]], Type[T]]: ...
68
69
70@dataclass_transform(eq_default=True, order_default=False)
71def typeannotation(
72 cls: Optional[Type[T]] = None, *, eq: bool = True, order: bool = False
73) -> Union[Type[T], Callable[[Type[T]], Type[T]]]:
74 """
75 Returns the same class as was passed in, with dunder methods added based on the fields defined in the class.
76
77 :param cls: The data-class type to transform into a type annotation.
78 :param eq: Whether to generate functions to support equality comparison.
79 :param order: Whether to generate functions to support ordering.
80 :returns: A data-class type, or a wrapper for data-class types.
81 """
82
83 def wrap(cls: Type[T]) -> Type[T]:
84 setattr(cls, "__repr__", _compact_dataclass_repr)
85 if not dataclasses.is_dataclass(cls):
86 cls = dataclasses.dataclass( # type: ignore[call-overload]
87 cls,
88 init=True,
89 repr=False,
90 eq=eq,
91 order=order,
92 unsafe_hash=False,
93 frozen=True,
94 )
95 return cls
96
97 # see if decorator is used as @typeannotation or @typeannotation()
98 if cls is None:
99 # called with parentheses
100 return wrap
101 else:
102 # called without parentheses
103 return wrap(cls)
104
105
106@typeannotation
107class Alias:
108 "Alternative name of a property, typically used in JSON serialization."
109
110 name: str
111
112
113@typeannotation
114class Signed:
115 "Signedness of an integer type."
116
117 is_signed: bool
118
119
120@typeannotation
121class Storage:
122 "Number of bytes the binary representation of an integer type takes, e.g. 4 bytes for an int32."
123
124 bytes: int
125
126
127@typeannotation
128class IntegerRange:
129 "Minimum and maximum value of an integer. The range is inclusive."
130
131 minimum: int
132 maximum: int
133
134
135@typeannotation
136class Precision:
137 "Precision of a floating-point value."
138
139 significant_digits: int
140 decimal_digits: int = 0
141
142 @property
143 def integer_digits(self) -> int:
144 return self.significant_digits - self.decimal_digits
145
146
147@typeannotation
148class TimePrecision:
149 """
150 Precision of a timestamp or time interval.
151
152 :param decimal_digits: Number of fractional digits retained in the sub-seconds field for a timestamp.
153 """
154
155 decimal_digits: int = 0
156
157
158@typeannotation
159class Length:
160 "Exact length of a string."
161
162 value: int
163
164
165@typeannotation
166class MinLength:
167 "Minimum length of a string."
168
169 value: int
170
171
172@typeannotation
173class MaxLength:
174 "Maximum length of a string."
175
176 value: int
177
178
179@typeannotation
180class SpecialConversion:
181 "Indicates that the annotated type is subject to custom conversion rules."
182
183
184int8: TypeAlias = Annotated[int, Signed(True), Storage(1), IntegerRange(-128, 127)]
185int16: TypeAlias = Annotated[int, Signed(True), Storage(2), IntegerRange(-32768, 32767)]
186int32: TypeAlias = Annotated[
187 int,
188 Signed(True),
189 Storage(4),
190 IntegerRange(-2147483648, 2147483647),
191]
192int64: TypeAlias = Annotated[
193 int,
194 Signed(True),
195 Storage(8),
196 IntegerRange(-9223372036854775808, 9223372036854775807),
197]
198
199uint8: TypeAlias = Annotated[int, Signed(False), Storage(1), IntegerRange(0, 255)]
200uint16: TypeAlias = Annotated[int, Signed(False), Storage(2), IntegerRange(0, 65535)]
201uint32: TypeAlias = Annotated[
202 int,
203 Signed(False),
204 Storage(4),
205 IntegerRange(0, 4294967295),
206]
207uint64: TypeAlias = Annotated[
208 int,
209 Signed(False),
210 Storage(8),
211 IntegerRange(0, 18446744073709551615),
212]
213
214float32: TypeAlias = Annotated[float, Storage(4)]
215float64: TypeAlias = Annotated[float, Storage(8)]
216
217# maps globals of type Annotated[T, ...] defined in this module to their string names
218_auxiliary_types: Dict[object, str] = {}
219module = sys.modules[__name__]
220for var in dir(module):
221 typ = getattr(module, var)
222 if getattr(typ, "__metadata__", None) is not None:
223 # type is Annotated[T, ...]
224 _auxiliary_types[typ] = var
225
226
227def get_auxiliary_format(data_type: object) -> Optional[str]:
228 "Returns the JSON format string corresponding to an auxiliary type."
229
230 return _auxiliary_types.get(data_type)