-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtyping.py
More file actions
378 lines (244 loc) · 8.29 KB
/
typing.py
File metadata and controls
378 lines (244 loc) · 8.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# mypy: ignore-errors
import contextvars
import typing
import types
from typing import Literal, Unpack
from typing import (
_GenericAlias,
_LiteralGenericAlias,
_UnpackGenericAlias,
)
_SpecialForm: typing.Any = typing._SpecialForm
###
# Here is a bunch of annoying internals stuff!
class _TupleLikeOperator:
@classmethod
def __class_getitem__(cls, args):
# Return an _IterSafeGenericAlias instead of a _GenericAlias
res = super().__class_getitem__(args)
return _IterSafeGenericAlias(res.__origin__, res.__args__)
# The base _GenericAlias has an __iter__ method that returns
# Unpack[self], which blows up when it's passed to something and
# doesn't have a tuple inside (because it hasn't been evaluated yet!).
# So we make own _GenericAlias that makes our own _UnpackGenericAlias
# that we make sure works.
#
# Probably these exact hacks will need to go into our
# typing_extensions version of this, but for the typing version they
# can get merged into real classes.
class _IterSafeGenericAlias(_GenericAlias, _root=True):
def __iter__(self):
yield _IterSafeUnpackGenericAlias(origin=Unpack, args=(self,))
class _IterSafeUnpackGenericAlias(_UnpackGenericAlias, _root=True):
@property
def __typing_unpacked_tuple_args__(self):
# This is basically the same as in _UnpackGenericAlias except
# we don't blow up if the origin isn't a tuple.
assert self.__origin__ is Unpack
assert len(self.__args__) == 1
(arg,) = self.__args__
if isinstance(arg, (_GenericAlias, types.GenericAlias)):
if arg.__origin__ is tuple:
return arg.__args__
return None
###
def has_associated_types(ocls):
def __class_getitem__(cls, args):
# Return an _HasAssociatedTypesGenericAlias instead of a _GenericAlias
res = super(ocls, cls).__class_getitem__(args)
return _HasAssociatedTypesGenericAlias(res.__origin__, res.__args__)
ocls.__class_getitem__ = classmethod(__class_getitem__)
return ocls
class _AssociatedTypeGenericAlias(_GenericAlias, _root=True):
pass
class _AssociatedType[Obj, Alias]:
pass
class _HasAssociatedTypesGenericAlias(_GenericAlias, _root=True):
def __getattr__(self, attr):
res = super().__getattr__(attr)
if isinstance(res, typing.TypeAliasType):
res = _AssociatedTypeGenericAlias(_AssociatedType, (self, res))
return res
###
# Not type-level computation but related
class BaseTypedDict(typing.TypedDict):
pass
class SpecialFormEllipsis:
pass
###
class _GenericCallableGenericAlias(_GenericAlias, _root=True):
def __repr__(self):
from typing import _type_repr
name = _type_repr(self.__origin__)
if self.__args__:
rargs = [_type_repr(self.__args__[0]), "<...>"]
args = ", ".join(rargs)
else:
# To ensure the repr is eval-able.
args = "()"
return f'{name}[{args}]'
class GenericCallable:
def __class_getitem__(cls, params):
message = (
"GenericCallable must be used as "
"GenericCallable[tuple[TypeVar, ...], lambda <vs>: callable]."
)
if not isinstance(params, tuple) or len(params) != 2:
raise TypeError(message)
typevars, func = params
if not callable(func):
raise TypeError(message)
return _GenericCallableGenericAlias(cls, (typevars, func))
class Overloaded[*Callables]:
pass
###
class InitField[KwargDict: BaseTypedDict]:
"""Base class to support dataclass.Field type initializers!
Will require some magical treatment in typecheckers...
"""
__kwargs: KwargDict
def __init__(self, **kwargs: typing.Unpack[KwargDict]) -> None:
self.__kwargs = kwargs
def get_kwargs(self) -> KwargDict:
return self.__kwargs
def __repr__(self) -> str:
args = ', '.join(f'{k}={v!r}' for k, v in self.__kwargs.items())
return f'{type(self).__name__}({args})'
###
class GetAnnotations[T]:
"""Fetch the annotations of a potentially Annotated type, as Literals.
GetAnnotations[Annotated[int, 'xxx']] = Literal['xxx']
GetAnnotations[Annotated[int, 'xxx', 5]] = Literal['xxx', 5]
GetAnnotations[int] = Never
"""
class DropAnnotations[T]:
"""Drop the annotations of a potentially Annotated type
DropAnnotations[Annotated[int, 'xxx']] = int
DropAnnotations[Annotated[int, 'xxx', 5]] = int
DropAnnotations[int] = int
"""
###
MemberQuals = Literal["ClassVar", "Final", "NotRequired", "ReadOnly"]
@has_associated_types
class Member[
N: str,
T,
Q: MemberQuals = typing.Never,
I = typing.Never,
D = typing.Never,
]:
type name = N
type type = T
type quals = Q
type init = I
type definer = D
ParamQuals = Literal["*", "**", "keyword", "positional", "default"]
@has_associated_types
class Param[N: str | None, T, Q: ParamQuals = typing.Never]:
type name = N
type type = T
type quals = Q
type PosParam[N: str | None, T] = Param[N, T, Literal["positional"]]
type PosDefaultParam[N: str | None, T] = Param[
N, T, Literal["positional", "default"]
]
type DefaultParam[N: str, T] = Param[N, T, Literal["default"]]
type NamedParam[N: str, T] = Param[N, T, Literal["keyword"]]
type NamedDefaultParam[N: str, T] = Param[N, T, Literal["keyword", "default"]]
type ArgsParam[T] = Param[Literal[None], T, Literal["*"]]
type KwargsParam[T] = Param[Literal[None], T, Literal["**"]]
type GetName[T: Member | Param] = T.name
type GetType[T: Member | Param] = T.type
type GetQuals[T: Member | Param] = T.quals
type GetInit[T: Member] = T.init
type GetDefiner[T: Member] = T.definer
class Attrs[T](_TupleLikeOperator):
pass
class Members[T](_TupleLikeOperator):
pass
class FromUnion[T](_TupleLikeOperator):
pass
class GetMember[Lhs, Prop]:
pass
class GetMemberType[Lhs, Prop]:
pass
class GetArg[Tp, Base, Idx: int]:
pass
class GetArgs[Tp, Base](_TupleLikeOperator):
pass
class GetSpecialAttr[T: type, Attr: str]:
pass
class Length[S: tuple]:
pass
class Slice[S: str | tuple, Start: int | None, End: int | None](
_TupleLikeOperator
):
pass
class Uppercase[S: str]:
pass
class Lowercase[S: str]:
pass
class Capitalize[S: str]:
pass
class Uncapitalize[S: str]:
pass
class StrConcat[S: str, T: str]:
pass
class NewProtocol[*T]:
pass
class NewTypedDict[*T]:
pass
class UpdateClass[*Ms]:
pass
class RaiseError[S: str, *Ts]:
"""Raise a type error with the given message when evaluated.
RaiseError[S: Literal[str], *Ts]: If this type needs to be evaluated
to determine some actual type, generate a type error with the
provided message.
Any additional type arguments should be included in the message.
"""
pass
##################################################################
# TODO: type better
special_form_evaluator: contextvars.ContextVar[
typing.Callable[[typing.Any], typing.Any] | None
] = contextvars.ContextVar("special_form_evaluator", default=None)
class _IterGenericAlias(_GenericAlias, _root=True):
def __iter__(self):
evaluator = special_form_evaluator.get()
if evaluator:
return evaluator(self)
else:
return iter(())
@_SpecialForm
def Iter(self, tp):
return _IterGenericAlias(self, (tp,))
class _BoolGenericAlias(_GenericAlias, _root=True):
def __bool__(self):
evaluator = special_form_evaluator.get()
if evaluator:
result = evaluator(self)
# Unwrap _LiteralGeneric
return bool(result)
else:
return False
@_SpecialForm
def IsAssignable(self, tps):
return _BoolGenericAlias(self, tps)
@_SpecialForm
def IsEquivalent(self, tps):
return _BoolGenericAlias(self, tps)
@_SpecialForm
def Bool(self, tp):
return _BoolGenericAlias(self, tp)
class _BoolLiteralGenericAlias(_LiteralGenericAlias, _root=True):
def __bool__(self):
return typing.get_args(self)[0]
@_SpecialForm
def _BoolLiteral(self, tp):
if isinstance(tp, type):
raise TypeError(f"Expected literal type, got '{tp.__name__}'")
# If already wrapped, just return it
if isinstance(tp, _BoolLiteralGenericAlias):
return tp
return _BoolLiteralGenericAlias(Literal, tp)