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
1
+ import collections.abc
2
+ import io
3
+ import itertools
4
+ import typing
5
+
6
+ def isoftype(object, type):
7
+ """
8
+ Checks if an object is of a certain typing type, including nested types.
9
+
10
+ This function supports simple types (like `int`, `str`), typing types
11
+ (like `List[int]`, `Tuple[str, int]`, `Dict[str, int]`), and nested typing
12
+ types (like `List[List[int]]`, `Tuple[List[str], int]`, `Dict[str, List[int]]`).
13
+
14
+ Args:
15
+ object: The object to check.
16
+ type: The typing type to check against.
17
+
18
+ Returns:
19
+ bool: True if the object is of the specified type, False otherwise.
20
+
21
+ Examples:
22
+ >>> isoftype(1, int)
23
+ True
24
+ >>> isoftype([1, 2, 3], typing.List[int])
25
+ True
26
+ >>> isoftype([1, 2, 3], typing.List[str])
27
+ False
28
+ >>> isoftype([[1, 2], [3, 4]], typing.List[typing.List[int]])
29
+ True
30
+ """
31
+
32
+ if hasattr(type, '__origin__'):
33
+ origin = type.__origin__
34
+ type_args = typing.get_args(type)
35
+
36
+ if origin is list or origin is set:
37
+ return all(isoftype(element, type_args[0]) for element in object)
38
+ elif origin is dict:
39
+ return all(isoftype(key, type_args[0]) and isoftype(value, type_args[1]) for key, value in object.items())
40
+ elif origin is tuple:
41
+ return all(isoftype(element, type_arg) for element, type_arg in zip(object, type_args))
42
+ else:
43
+ return isinstance(object, type)
44
+
45
+ # copied from: https://github.com/bojiang/typing_utils/blob/main/typing_utils/__init__.py
46
+ # liscened under Apache License 2.0
47
+
48
+
49
+ if hasattr(typing, "ForwardRef"): # python3.8
50
+ ForwardRef = getattr(typing, "ForwardRef")
51
+ elif hasattr(typing, "_ForwardRef"): # python3.6
52
+ ForwardRef = getattr(typing, "_ForwardRef")
53
+ else:
54
+ raise NotImplementedError()
55
+
56
+
57
+ unknown = None
58
+
59
+
60
+ BUILTINS_MAPPING = {
61
+ typing.List: list,
62
+ typing.Set: set,
63
+ typing.Dict: dict,
64
+ typing.Tuple: tuple,
65
+ typing.ByteString: bytes, # https://docs.python.org/3/library/typing.html#typing.ByteString
66
+ typing.Callable: collections.abc.Callable,
67
+ typing.Sequence: collections.abc.Sequence,
68
+ type(None): None,
69
+ }
70
+
71
+
72
+ STATIC_SUBTYPE_MAPPING: typing.Dict[type, typing.Type] = {
73
+ io.TextIOWrapper: typing.TextIO,
74
+ io.TextIOBase: typing.TextIO,
75
+ io.StringIO: typing.TextIO,
76
+ io.BufferedReader: typing.BinaryIO,
77
+ io.BufferedWriter: typing.BinaryIO,
78
+ io.BytesIO: typing.BinaryIO,
79
+ }
80
+
81
+
82
+ def optional_all(elements) -> typing.Optional[bool]:
83
+ if all(elements):
84
+ return True
85
+ if all(e is False for e in elements):
86
+ return False
87
+ return unknown
88
+
89
+
90
+ def optional_any(elements) -> typing.Optional[bool]:
91
+ if any(elements):
92
+ return True
93
+ if any(e is None for e in elements):
94
+ return unknown
95
+ return False
96
+
97
+
98
+ def _hashable(value):
99
+ """Determine whether `value` can be hashed."""
100
+ try:
101
+ hash(value)
102
+ except TypeError:
103
+ return False
104
+ return True
105
+
106
+
107
+ get_type_hints = typing.get_type_hints
108
+
109
+ GenericClass = type(typing.List)
110
+ UnionClass = type(typing.Union)
111
+
112
+ Type = typing.Union[None, type, "typing.TypeVar"]
113
+ OriginType = typing.Union[None, type]
114
+ TypeArgs = typing.Union[type, typing.AbstractSet[type], typing.Sequence[type]]
115
+
116
+
117
+ def _normalize_aliases(type_: Type) -> Type:
118
+ if isinstance(type_, typing.TypeVar):
119
+ return type_
120
+
121
+ assert _hashable(type_), "_normalize_aliases should only be called on element types"
122
+
123
+ if type_ in BUILTINS_MAPPING:
124
+ return BUILTINS_MAPPING[type_]
125
+ return type_
126
+
127
+
128
+ def get_origin(type_):
129
+ """Get the unsubscripted version of a type.
130
+ This supports generic types, Callable, Tuple, Union, Literal, Final and ClassVar.
131
+ Return None for unsupported types.
132
+
133
+ Examples:
134
+
135
+ ```python
136
+ from typing_utils import get_origin
137
+
138
+ get_origin(Literal[42]) is Literal
139
+ get_origin(int) is None
140
+ get_origin(ClassVar[int]) is ClassVar
141
+ get_origin(Generic) is Generic
142
+ get_origin(Generic[T]) is Generic
143
+ get_origin(Union[T, int]) is Union
144
+ get_origin(List[Tuple[T, T]][int]) == list
145
+ ```
146
+ """
147
+ if hasattr(typing, 'get_origin'): # python 3.8+
148
+ _getter = getattr(typing, "get_origin")
149
+ ori = _getter(type_)
150
+ elif hasattr(typing.List, "_special"): # python 3.7
151
+ if isinstance(type_, GenericClass) and not type_._special:
152
+ ori = type_.__origin__
153
+ elif hasattr(type_, "_special") and type_._special:
154
+ ori = type_
155
+ elif type_ is typing.Generic:
156
+ ori = typing.Generic
157
+ else:
158
+ ori = None
159
+ else: # python 3.6
160
+ if isinstance(type_, GenericClass):
161
+ ori = type_.__origin__
162
+ if ori is None:
163
+ ori = type_
164
+ elif isinstance(type_, UnionClass):
165
+ ori = type_.__origin__
166
+ elif type_ is typing.Generic:
167
+ ori = typing.Generic
168
+ else:
169
+ ori = None
170
+ return _normalize_aliases(ori)
171
+
172
+
173
+ def get_args(type_) -> typing.Tuple:
174
+ """Get type arguments with all substitutions performed.
175
+ For unions, basic simplifications used by Union constructor are performed.
176
+
177
+ Examples:
178
+
179
+ ```python
180
+ from typing_utils import get_args
181
+
182
+ get_args(Dict[str, int]) == (str, int)
183
+ get_args(int) == ()
184
+ get_args(Union[int, Union[T, int], str][int]) == (int, str)
185
+ get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
186
+ get_args(Callable[[], T][int]) == ([], int)
187
+ ```
188
+ """
189
+ if hasattr(typing, 'get_args'): # python 3.8+
190
+ _getter = getattr(typing, "get_args")
191
+ res = _getter(type_)
192
+ elif hasattr(typing.List, "_special"): # python 3.7
193
+ if (
194
+ isinstance(type_, GenericClass) and not type_._special
195
+ ): # backport for python 3.8
196
+ res = type_.__args__
197
+ if get_origin(type_) is collections.abc.Callable and res[0] is not Ellipsis:
198
+ res = (list(res[:-1]), res[-1])
199
+ else:
200
+ res = ()
201
+ else: # python 3.6
202
+ if isinstance(type_, (GenericClass, UnionClass)): # backport for python 3.8
203
+ res = type_.__args__
204
+ if get_origin(type_) is collections.abc.Callable and res[0] is not Ellipsis:
205
+ res = (list(res[:-1]), res[-1])
206
+ else:
207
+ res = ()
208
+ return () if res is None else res
209
+
210
+
211
+ def eval_forward_ref(ref, forward_refs=None):
212
+ '''
213
+ eval forward_refs in all cPython versions
214
+ '''
215
+ localns = forward_refs or {}
216
+
217
+ if hasattr(typing, "_eval_type"): # python3.8 & python 3.9
218
+ _eval_type = getattr(typing, "_eval_type")
219
+ return _eval_type(ref, globals(), localns)
220
+
221
+ if hasattr(ref, "_eval_type"): # python3.6
222
+ _eval_type = getattr(ref, "_eval_type")
223
+ return _eval_type(globals(), localns)
224
+
225
+ raise NotImplementedError()
226
+
227
+
228
+ class NormalizedType(typing.NamedTuple):
229
+ '''
230
+ Normalized type, made it possible to compare, hash between types.
231
+ '''
232
+
233
+ origin: Type
234
+ args: typing.Union[tuple, frozenset] = tuple()
235
+
236
+ def __eq__(self, other):
237
+ if isinstance(other, NormalizedType):
238
+ if self.origin != other.origin:
239
+ return False
240
+ if isinstance(self.args, frozenset) and isinstance(other.args, frozenset):
241
+ return self.args <= other.args and other.args <= self.args
242
+ return self.origin == other.origin and self.args == other.args
243
+ if not self.args:
244
+ return self.origin == other
245
+ return False
246
+
247
+ def __hash__(self) -> int:
248
+ if not self.args:
249
+ return hash(self.origin)
250
+ return hash((self.origin, self.args))
251
+
252
+ def __repr__(self):
253
+ if not self.args:
254
+ return f"{self.origin}"
255
+ return f"{self.origin}[{self.args}])"
256
+
257
+
258
+ def _normalize_args(tps: TypeArgs):
259
+ if isinstance(tps, str):
260
+ return tps
261
+ if isinstance(tps, collections.abc.Sequence):
262
+ return tuple(_normalize_args(type_) for type_ in tps)
263
+ if isinstance(tps, collections.abc.Set):
264
+ return frozenset(_normalize_args(type_) for type_ in tps)
265
+ return normalize(tps)
266
+
267
+
268
+ def normalize(type_: Type) -> NormalizedType:
269
+ '''
270
+ convert types to NormalizedType instances.
271
+ '''
272
+ args = get_args(type_)
273
+ origin = get_origin(type_)
274
+ if not origin:
275
+ return NormalizedType(_normalize_aliases(type_))
276
+ origin = _normalize_aliases(origin)
277
+
278
+ if origin is typing.Union: # sort args when the origin is Union
279
+ args = _normalize_args(frozenset(args))
280
+ else:
281
+ args = _normalize_args(args)
282
+ return NormalizedType(origin, args)
283
+
284
+
285
+ def _is_origin_subtype(left: OriginType, right: OriginType) -> bool:
286
+ if left is right:
287
+ return True
288
+
289
+ if (
290
+ left is not None
291
+ and left in STATIC_SUBTYPE_MAPPING
292
+ and right == STATIC_SUBTYPE_MAPPING[left]
293
+ ):
294
+ return True
295
+
296
+ if hasattr(left, "mro"):
297
+ for parent in left.mro():
298
+ if parent == right:
299
+ return True
300
+
301
+ if isinstance(left, type) and isinstance(right, type):
302
+ return issubclass(left, right)
303
+
304
+ return left == right
305
+
306
+
307
+ NormalizedTypeArgs = typing.Union[
308
+ typing.Tuple["NormalizedTypeArgs", ...],
309
+ typing.FrozenSet[NormalizedType],
310
+ NormalizedType,
311
+ ]
312
+
313
+
314
+ def _is_origin_subtype_args(
315
+ left: NormalizedTypeArgs,
316
+ right: NormalizedTypeArgs,
317
+ forward_refs: typing.Optional[typing.Mapping[str, type]],
318
+ ) -> typing.Optional[bool]:
319
+ if isinstance(left, frozenset):
320
+ if not isinstance(right, frozenset):
321
+ return False
322
+
323
+ excluded = left - right
324
+ if not excluded:
325
+ # Union[str, int] <> Union[int, str]
326
+ return True
327
+
328
+ # Union[list, int] <> Union[typing.Sequence, int]
329
+ return all(
330
+ any(_is_normal_subtype(e, r, forward_refs) for r in right) for e in excluded
331
+ )
332
+
333
+ if isinstance(left, collections.abc.Sequence) and not isinstance(
334
+ left, NormalizedType
335
+ ):
336
+ if not isinstance(right, collections.abc.Sequence) or isinstance(
337
+ right, NormalizedType
338
+ ):
339
+ return False
340
+
341
+ if (
342
+ left
343
+ and left[-1].origin is not Ellipsis
344
+ and right
345
+ and right[-1].origin is Ellipsis
346
+ ):
347
+ # Tuple[type, type] <> Tuple[type, ...]
348
+ return all(_is_origin_subtype_args(l, right[0], forward_refs) for l in left)
349
+
350
+ if len(left) != len(right):
351
+ return False
352
+
353
+ return all(
354
+ l is not None
355
+ and r is not None
356
+ and _is_origin_subtype_args(l, r, forward_refs)
357
+ for l, r in itertools.zip_longest(left, right)
358
+ )
359
+
360
+ assert isinstance(left, NormalizedType)
361
+ assert isinstance(right, NormalizedType)
362
+
363
+ return _is_normal_subtype(left, right, forward_refs)
364
+
365
+
366
+ def _is_normal_subtype(
367
+ left: NormalizedType,
368
+ right: NormalizedType,
369
+ forward_refs: typing.Optional[typing.Mapping[str, type]],
370
+ ) -> typing.Optional[bool]:
371
+
372
+ if isinstance(left.origin, ForwardRef):
373
+ left = normalize(eval_forward_ref(left.origin, forward_refs=forward_refs))
374
+
375
+ if isinstance(right.origin, ForwardRef):
376
+ right = normalize(eval_forward_ref(right.origin, forward_refs=forward_refs))
377
+
378
+ # Any
379
+ if right.origin is typing.Any:
380
+ return True
381
+
382
+ # Union
383
+ if right.origin is typing.Union and left.origin is typing.Union:
384
+ return _is_origin_subtype_args(left.args, right.args, forward_refs)
385
+ if right.origin is typing.Union:
386
+ return optional_any(
387
+ _is_normal_subtype(left, a, forward_refs) for a in right.args
388
+ )
389
+ if left.origin is typing.Union:
390
+ return optional_all(
391
+ _is_normal_subtype(a, right, forward_refs) for a in left.args
392
+ )
393
+
394
+ # TypeVar
395
+ if isinstance(left.origin, typing.TypeVar) and isinstance(
396
+ right.origin, typing.TypeVar
397
+ ):
398
+ if left.origin is right.origin:
399
+ return True
400
+
401
+ left_bound = getattr(left.origin, "__bound__", None)
402
+ right_bound = getattr(right.origin, "__bound__", None)
403
+ if right_bound is None or left_bound is None:
404
+ return unknown
405
+ return _is_normal_subtype(
406
+ normalize(left_bound), normalize(right_bound), forward_refs
407
+ )
408
+ if isinstance(right.origin, typing.TypeVar):
409
+ return unknown
410
+ if isinstance(left.origin, typing.TypeVar):
411
+ left_bound = getattr(left.origin, "__bound__", None)
412
+ if left_bound is None:
413
+ return unknown
414
+ return _is_normal_subtype(normalize(left_bound), right, forward_refs)
415
+
416
+ if not left.args and not right.args:
417
+ return _is_origin_subtype(left.origin, right.origin)
418
+
419
+ if not right.args:
420
+ return _is_origin_subtype(left.origin, right.origin)
421
+
422
+ if _is_origin_subtype(left.origin, right.origin):
423
+ return _is_origin_subtype_args(left.args, right.args, forward_refs)
424
+
425
+ return False
426
+
427
+
428
+ def issubtype(
429
+ left: Type, right: Type, forward_refs: typing.Optional[dict] = None,
430
+ ) -> typing.Optional[bool]:
431
+ """Check that the left argument is a subtype of the right.
432
+ For unions, check if the type arguments of the left is a subset of the right.
433
+ Also works for nested types including ForwardRefs.
434
+
435
+ Examples:
436
+
437
+ ```python
438
+ from typing_utils import issubtype
439
+
440
+ issubtype(typing.List, typing.Any) == True
441
+ issubtype(list, list) == True
442
+ issubtype(list, typing.List) == True
443
+ issubtype(list, typing.Sequence) == True
444
+ issubtype(typing.List[int], list) == True
445
+ issubtype(typing.List[typing.List], list) == True
446
+ issubtype(list, typing.List[int]) == False
447
+ issubtype(list, typing.Union[typing.Tuple, typing.Set]) == False
448
+ issubtype(typing.List[typing.List], typing.List[typing.Sequence]) == True
449
+ JSON = typing.Union[
450
+ int, float, bool, str, None, typing.Sequence["JSON"],
451
+ typing.Mapping[str, "JSON"]
452
+ ]
453
+ issubtype(str, JSON, forward_refs={'JSON': JSON}) == True
454
+ issubtype(typing.Dict[str, str], JSON, forward_refs={'JSON': JSON}) == True
455
+ issubtype(typing.Dict[str, bytes], JSON, forward_refs={'JSON': JSON}) == False
456
+ ```
457
+ """
458
+ return _is_normal_subtype(normalize(left), normalize(right), forward_refs)