forked from yukinarit/pyserde
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompat.py
More file actions
1171 lines (973 loc) · 28.6 KB
/
compat.py
File metadata and controls
1171 lines (973 loc) · 28.6 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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Compatibility layer which handles mostly differences of `typing` module between python versions.
"""
import dataclasses
import datetime
import decimal
import enum
import functools
import ipaddress
import itertools
import pathlib
import types
import uuid
import typing
import typing_extensions
from collections import defaultdict, deque, Counter
from collections.abc import Iterator, Sequence, MutableSequence
from collections.abc import Mapping, MutableMapping, Set, MutableSet
from dataclasses import is_dataclass
from typing import TypeVar, Generic, Any, ClassVar, Optional, NewType, Union, Hashable, Callable
import typing_inspect
from typing_extensions import TypeGuard, ParamSpec
# `typing_extensions.TypeAliasType` isn't always an alias to `typing.TypeAliasType`
# depending on certain versions of `typing_extensions` and python.
_PEP695_TYPES: tuple[type, ...]
if hasattr(typing, "TypeAliasType"):
_PEP695_TYPES = (typing_extensions.TypeAliasType, typing.TypeAliasType)
else:
_PEP695_TYPES = (typing_extensions.TypeAliasType,)
# Lazy SQLAlchemy imports to improve startup time
# Lazy SQLAlchemy import wrapper to improve startup time
def _is_sqlalchemy_inspectable(subject: Any) -> bool:
from .sqlalchemy import is_sqlalchemy_inspectable
return is_sqlalchemy_inspectable(subject)
def get_np_origin(tp: type[Any]) -> Any | None:
return None
def get_np_args(tp: type[Any]) -> tuple[Any, ...]:
return ()
__all__: list[str] = []
T = TypeVar("T")
StrSerializableTypes = (
decimal.Decimal,
pathlib.Path,
pathlib.PosixPath,
pathlib.WindowsPath,
pathlib.PurePath,
pathlib.PurePosixPath,
pathlib.PureWindowsPath,
uuid.UUID,
ipaddress.IPv4Address,
ipaddress.IPv6Address,
ipaddress.IPv4Network,
ipaddress.IPv6Network,
ipaddress.IPv4Interface,
ipaddress.IPv6Interface,
)
""" List of standard types (de)serializable to str """
DateTimeTypes = (datetime.date, datetime.time, datetime.datetime)
""" List of datetime types """
@dataclasses.dataclass(unsafe_hash=True)
class _WithTagging(Generic[T]):
"""
Intermediate data structure for (de)serializaing Union without dataclass.
"""
inner: T
""" Union type .e.g Union[Foo,Bar] passed in from_obj. """
tagging: Any
""" Union Tagging """
class SerdeError(Exception):
"""
Serde error class.
"""
@dataclasses.dataclass
class UserError(Exception):
"""
Error from user code e.g. __post_init__.
"""
inner: Exception
class SerdeSkip(Exception):
"""
Skip a field in custom (de)serializer.
"""
def is_hashable(typ: Any) -> TypeGuard[Hashable]:
"""
Test is an object hashable
"""
try:
hash(typ)
except TypeError:
return False
return True
P = ParamSpec("P")
def cache(f: Callable[P, T]) -> Callable[P, T]:
"""
Wrapper for `functools.cache` to avoid `Hashable` related type errors.
"""
def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
return f(*args, **kwargs)
return functools.cache(wrapper) # type: ignore
@cache
def get_origin(typ: Any) -> Any | None:
"""
Provide `get_origin` that works in all python versions.
"""
return typing.get_origin(typ) or get_np_origin(typ)
@cache
def get_args(typ: type[Any]) -> tuple[Any, ...]:
"""
Provide `get_args` that works in all python versions.
"""
return typing.get_args(typ) or get_np_args(typ)
@cache
def typename(typ: Any, with_typing_module: bool = False) -> str:
"""
>>> from typing import Any
>>> typename(int)
'int'
>>> class Foo: pass
>>> typename(Foo)
'Foo'
>>> typename(list[Foo])
'list[Foo]'
>>> typename(dict[str, Foo])
'dict[str, Foo]'
>>> typename(tuple[int, str, Foo, list[int], dict[str, Foo]])
'tuple[int, str, Foo, list[int], dict[str, Foo]]'
>>> typename(Optional[list[Foo]])
'Optional[list[Foo]]'
>>> typename(Union[Optional[Foo], list[Foo], Union[str, int]])
'Union[Optional[Foo], list[Foo], str, int]'
>>> typename(set[Foo])
'set[Foo]'
>>> typename(Any)
'Any'
"""
mod = "typing." if with_typing_module else ""
thisfunc = functools.partial(typename, with_typing_module=with_typing_module)
if is_opt(typ):
args = type_args(typ)
if args:
return f"{mod}Optional[{thisfunc(type_args(typ)[0])}]"
else:
return f"{mod}Optional"
elif is_union(typ):
args = union_args(typ)
if args:
return f'{mod}Union[{", ".join([thisfunc(e) for e in args])}]'
else:
return f"{mod}Union"
elif is_list(typ):
args = type_args(typ)
if args:
et = thisfunc(args[0])
return f"{mod}list[{et}]"
else:
return f"{mod}list"
elif is_set(typ):
args = type_args(typ)
if args:
et = thisfunc(args[0])
return f"{mod}set[{et}]"
else:
return f"{mod}set"
elif is_dict(typ):
args = type_args(typ)
if args and len(args) == 2:
kt = thisfunc(args[0])
vt = thisfunc(args[1])
return f"{mod}dict[{kt}, {vt}]"
else:
return f"{mod}dict"
elif is_deque(typ):
args = type_args(typ)
if args:
et = thisfunc(args[0])
return f"deque[{et}]"
else:
return "deque"
elif is_counter(typ):
args = type_args(typ)
if args:
et = thisfunc(args[0])
return f"Counter[{et}]"
else:
return "Counter"
elif is_tuple(typ):
args = type_args(typ)
if args:
return f'{mod}tuple[{", ".join([thisfunc(e) for e in args])}]'
else:
return f"{mod}tuple"
elif is_generic(typ):
origin = get_origin(typ)
if origin is None:
raise SerdeError("Could not extract origin class from generic class")
if not isinstance(origin.__name__, str):
raise SerdeError("Name of generic class is not string")
return origin.__name__
elif is_literal(typ):
args = type_args(typ)
if not args:
raise TypeError("Literal type requires at least one literal argument")
return f'Literal[{", ".join(stringify_literal(e) for e in args)}]'
elif typ is Any:
return f"{mod}Any"
elif is_ellipsis(typ):
return "..."
else:
# Get super type for NewType
inner = getattr(typ, "__supertype__", None)
if inner:
return typename(inner)
name: str | None = getattr(typ, "_name", None)
if name:
return name
else:
name = getattr(typ, "__name__", None)
if isinstance(name, str):
return name
else:
raise SerdeError(f"Could not get a type name from: {typ}")
def stringify_literal(v: Any) -> str:
if isinstance(v, str):
return f"'{v}'"
else:
return str(v)
def type_args(typ: Any) -> tuple[type[Any], ...]:
"""
Wrapper to suppress type error for accessing private members.
"""
try:
args: tuple[type[Any, ...]] | None = typ.__args__ # type: ignore
except AttributeError:
return get_args(typ)
# Some typing objects expose __args__ as a member_descriptor (e.g. typing.Union),
# which isn't iterable. Fall back to typing.get_args in that case.
if isinstance(args, tuple):
return args
return get_args(typ)
def union_args(typ: Any) -> tuple[type[Any], ...]:
if not is_union(typ):
raise TypeError(f"{typ} is not Union")
args = type_args(typ)
if len(args) == 1:
return (args[0],)
it = iter(args)
types = []
for i1, i2 in itertools.zip_longest(it, it):
if not i2:
types.append(i1)
elif is_none(i2):
types.append(Optional[i1])
else:
types.extend((i1, i2))
return tuple(types)
def dataclass_fields(cls: type[Any]) -> Iterator[dataclasses.Field]: # type: ignore
raw_fields = dataclasses.fields(cls)
try:
# this resolves types when string forward reference
# or PEP 563: "from __future__ import annotations" are used
resolved_hints = typing.get_type_hints(cls)
except Exception as e:
raise SerdeError(
f"Failed to resolve type hints for {typename(cls)}:\n"
f"{e.__class__.__name__}: {e}\n\n"
f"If you are using forward references make sure you are calling deserialize & "
"serialize after all classes are globally visible."
) from e
for f in raw_fields:
real_type = resolved_hints.get(f.name)
if real_type is not None:
f.type = real_type
if is_generic(real_type) and _is_sqlalchemy_inspectable(cls):
f.type = get_args(real_type)[0]
return iter(raw_fields)
TypeLike = Union[type[Any], typing.Any]
def iter_types(cls: type[Any]) -> list[type[Any]]:
"""
Iterate field types recursively.
The correct return type is `Iterator[Union[Type, typing._specialform]],
but `typing._specialform` doesn't exist for python 3.6. Use `Any` instead.
"""
lst: set[Union[type[Any], Any]] = set()
def recursive(cls: Union[type[Any], Any]) -> None:
if cls in lst:
return
if is_dataclass(cls):
lst.add(cls)
if isinstance(cls, type):
for f in dataclass_fields(cls):
recursive(f.type)
elif isinstance(cls, str):
lst.add(cls)
elif is_opt(cls):
lst.add(Optional)
args = type_args(cls)
if args:
recursive(args[0])
elif is_union(cls):
lst.add(Union)
for arg in type_args(cls):
recursive(arg)
elif is_list(cls):
lst.add(list)
args = type_args(cls)
if args:
recursive(args[0])
elif is_set(cls):
lst.add(set)
args = type_args(cls)
if args:
recursive(args[0])
elif is_deque(cls):
lst.add(deque)
args = type_args(cls)
if args:
recursive(args[0])
elif is_counter(cls):
lst.add(Counter)
args = type_args(cls)
if args:
recursive(args[0])
elif is_tuple(cls):
lst.add(tuple)
for arg in type_args(cls):
recursive(arg)
elif is_dict(cls):
lst.add(dict)
args = type_args(cls)
if args and len(args) >= 2:
recursive(args[0])
recursive(args[1])
elif is_pep695_type_alias(cls):
recursive(cls.__value__)
else:
lst.add(cls)
recursive(cls)
return list(lst)
def iter_unions(cls: TypeLike) -> list[TypeLike]:
"""
Iterate over all unions that are used in the dataclass
"""
lst: list[TypeLike] = []
stack: list[TypeLike] = [] # To prevent infinite recursion
def recursive(cls: TypeLike) -> None:
if cls in stack:
return
if is_union(cls):
lst.append(cls)
for arg in type_args(cls):
recursive(arg)
elif is_pep695_type_alias(cls):
recursive(cls.__value__)
if is_dataclass(cls):
stack.append(cls)
if isinstance(cls, type):
for f in dataclass_fields(cls):
if not f.metadata.get("serde_skip"):
recursive(f.type)
stack.pop()
elif is_opt(cls):
args = type_args(cls)
if args:
recursive(args[0])
elif is_list(cls) or is_set(cls) or is_deque(cls) or is_counter(cls):
args = type_args(cls)
if args:
recursive(args[0])
elif is_tuple(cls):
for arg in type_args(cls):
recursive(arg)
elif is_dict(cls):
args = type_args(cls)
if args and len(args) >= 2:
recursive(args[0])
recursive(args[1])
recursive(cls)
return lst
def iter_literals(cls: type[Any]) -> list[TypeLike]:
"""
Iterate over all literals that are used in the dataclass
"""
lst: set[Union[type[Any], Any]] = set()
stack: list[TypeLike] = [] # To prevent infinite recursion
def recursive(cls: Union[type[Any], Any]) -> None:
if cls in stack:
return
if is_literal(cls):
lst.add(cls)
if is_union(cls):
for arg in type_args(cls):
recursive(arg)
if is_dataclass(cls):
stack.append(cls)
if isinstance(cls, type):
for f in dataclass_fields(cls):
recursive(f.type)
stack.pop()
elif is_opt(cls):
args = type_args(cls)
if args:
recursive(args[0])
elif is_list(cls) or is_set(cls) or is_deque(cls) or is_counter(cls):
args = type_args(cls)
if args:
recursive(args[0])
elif is_tuple(cls):
for arg in type_args(cls):
recursive(arg)
elif is_dict(cls):
args = type_args(cls)
if args and len(args) >= 2:
recursive(args[0])
recursive(args[1])
recursive(cls)
return list(lst)
@cache
def is_union(typ: Any) -> bool:
"""
Test if the type is `typing.Union`.
>>> is_union(Union[int, str])
True
"""
try:
# When `_WithTagging` is received, it will check inner type.
if isinstance(typ, _WithTagging):
return is_union(typ.inner)
except Exception:
pass
# Python 3.10+ Union operator e.g. str | int
try:
if isinstance(typ, types.UnionType):
return True
except Exception:
pass
# typing.Union
return typing_inspect.is_union_type(typ) # type: ignore
@cache
def is_opt(typ: Any) -> bool:
"""
Test if the type is `typing.Optional`.
>>> is_opt(Optional[int])
True
>>> is_opt(Optional)
True
>>> is_opt(None.__class__)
False
"""
# Python 3.10+ Union operator e.g. str | None
is_union_type = False
try:
if isinstance(typ, types.UnionType):
is_union_type = True
except Exception:
pass
# typing.Optional
is_typing_union = typing_inspect.is_optional_type(typ)
args = type_args(typ)
if args:
return (
(is_union_type or is_typing_union)
and len(args) == 2
and not is_none(args[0])
and is_none(args[1])
)
else:
return typ is Optional
@cache
def is_bare_opt(typ: Any) -> bool:
"""
Test if the type is `typing.Optional` without type args.
>>> is_bare_opt(Optional[int])
False
>>> is_bare_opt(Optional)
True
>>> is_bare_opt(None.__class__)
False
"""
return not type_args(typ) and typ is Optional
@cache
def is_opt_dataclass(typ: Any) -> bool:
"""
Test if the type is optional dataclass.
>>> is_opt_dataclass(Optional[int])
False
>>> @dataclasses.dataclass
... class Foo:
... pass
>>> is_opt_dataclass(Foo)
False
>>> is_opt_dataclass(Optional[Foo])
False
"""
args = get_args(typ)
return is_opt(typ) and len(args) > 0 and is_dataclass(args[0])
@cache
def is_list(typ: type[Any]) -> bool:
"""
Test if the type is `list`, `collections.abc.Sequence`, or `collections.abc.MutableSequence`.
>>> is_list(list[int])
True
>>> is_list(list)
True
>>> is_list(Sequence[int])
True
>>> is_list(Sequence)
True
>>> is_list(MutableSequence[int])
True
>>> is_list(MutableSequence)
True
"""
origin = get_origin(typ)
if origin is None:
return typ in (list, Sequence, MutableSequence)
return origin in (list, Sequence, MutableSequence)
@cache
def is_bare_list(typ: type[Any]) -> bool:
"""
Test if the type is `list`/`collections.abc.Sequence`/`collections.abc.MutableSequence`
without type args.
>>> is_bare_list(list[int])
False
>>> is_bare_list(list)
True
>>> is_bare_list(Sequence[int])
False
>>> is_bare_list(Sequence)
True
>>> is_bare_list(MutableSequence[int])
False
>>> is_bare_list(MutableSequence)
True
"""
origin = get_origin(typ)
if origin in (list, Sequence, MutableSequence):
return not type_args(typ)
return typ in (list, Sequence, MutableSequence)
@cache
def is_tuple(typ: Any) -> bool:
"""
Test if the type is tuple.
"""
try:
return issubclass(get_origin(typ), tuple) # type: ignore
except TypeError:
return typ is tuple
@cache
def is_bare_tuple(typ: type[Any]) -> bool:
"""
Test if the type is tuple without type args.
>>> is_bare_tuple(tuple[int, str])
False
>>> is_bare_tuple(tuple)
True
"""
return typ is tuple
@cache
def is_variable_tuple(typ: type[Any]) -> bool:
"""
Test if the type is a variable length of tuple tuple[T, ...]`.
>>> is_variable_tuple(tuple[int, ...])
True
>>> is_variable_tuple(tuple[int, bool])
False
>>> is_variable_tuple(tuple[()])
False
"""
istuple = is_tuple(typ) and not is_bare_tuple(typ)
args = get_args(typ)
return istuple and len(args) == 2 and is_ellipsis(args[1])
@cache
def is_set(typ: type[Any]) -> bool:
"""
Test if the type is set-like.
>>> is_set(set[int])
True
>>> is_set(set)
True
>>> is_set(frozenset[int])
True
>>> from collections.abc import Set, MutableSet
>>> is_set(Set[int])
True
>>> is_set(Set)
True
>>> is_set(MutableSet[int])
True
>>> is_set(MutableSet)
True
"""
try:
return issubclass(get_origin(typ), (set, frozenset, Set, MutableSet)) # type: ignore[arg-type]
except TypeError:
return typ in (set, frozenset, Set, MutableSet)
@cache
def is_bare_set(typ: type[Any]) -> bool:
"""
Test if the type is `set`/`frozenset`/`Set`/`MutableSet` without type args.
>>> is_bare_set(set[int])
False
>>> is_bare_set(set)
True
>>> from collections.abc import Set, MutableSet
>>> is_bare_set(Set)
True
>>> is_bare_set(MutableSet)
True
"""
origin = get_origin(typ)
if origin in (set, frozenset, Set, MutableSet):
return not type_args(typ)
return typ in (set, frozenset, Set, MutableSet)
@cache
def is_frozen_set(typ: type[Any]) -> bool:
"""
Test if the type is `frozenset`.
>>> is_frozen_set(frozenset[int])
True
>>> is_frozen_set(set)
False
"""
try:
return issubclass(get_origin(typ), frozenset) # type: ignore
except TypeError:
return typ is frozenset
@cache
def is_dict(typ: type[Any]) -> bool:
"""
Test if the type is dict-like.
>>> is_dict(dict[int, int])
True
>>> is_dict(dict)
True
>>> is_dict(defaultdict[int, int])
True
>>> from collections.abc import Mapping, MutableMapping
>>> is_dict(Mapping[str, int])
True
>>> is_dict(Mapping)
True
>>> is_dict(MutableMapping[str, int])
True
>>> is_dict(MutableMapping)
True
"""
try:
return issubclass(
get_origin(typ), (dict, defaultdict, Mapping, MutableMapping) # type: ignore[arg-type]
)
except TypeError:
return typ in (dict, defaultdict, Mapping, MutableMapping)
def is_flatten_dict(typ: Any) -> bool:
"""
Test if the type is dict[str, Any] or bare dict suitable for flatten.
>>> is_flatten_dict(dict[str, Any])
True
>>> is_flatten_dict(dict)
True
>>> is_flatten_dict(dict[str, int])
False
>>> is_flatten_dict(dict[int, str])
False
>>> is_flatten_dict(list[str])
False
"""
if not is_dict(typ):
return False
# Allow bare dict
if is_bare_dict(typ):
return True
args = type_args(typ)
if not args or len(args) != 2:
return False
# Key must be str, value must be Any
return args[0] is str and is_any(args[1])
@cache
@cache
def is_bare_dict(typ: type[Any]) -> bool:
"""
Test if the type is `dict`/`Mapping`/`MutableMapping` without type args.
>>> is_bare_dict(dict[int, str])
False
>>> is_bare_dict(dict)
True
>>> from collections.abc import Mapping, MutableMapping
>>> is_bare_dict(Mapping)
True
>>> is_bare_dict(MutableMapping)
True
"""
origin = get_origin(typ)
if origin in (dict, Mapping, MutableMapping):
return not type_args(typ)
return typ in (dict, Mapping, MutableMapping)
@cache
def is_default_dict(typ: type[Any]) -> bool:
"""
Test if the type is `defaultdict`.
>>> is_default_dict(defaultdict[int, int])
True
>>> is_default_dict(dict[int, int])
False
"""
try:
return issubclass(get_origin(typ), defaultdict) # type: ignore
except TypeError:
return typ is defaultdict
@cache
def is_deque(typ: type[Any]) -> bool:
"""
Test if the type is `collections.deque`.
>>> is_deque(deque[int])
True
>>> is_deque(deque)
True
>>> is_deque(list[int])
False
"""
try:
return issubclass(get_origin(typ), deque) # type: ignore
except TypeError:
return typ is deque
@cache
def is_bare_deque(typ: type[Any]) -> bool:
"""
Test if the type is `collections.deque` without type args.
>>> is_bare_deque(deque[int])
False
>>> is_bare_deque(deque)
True
"""
origin = get_origin(typ)
if origin is deque:
return not type_args(typ)
return typ is deque
@cache
def is_counter(typ: type[Any]) -> bool:
"""
Test if the type is `collections.Counter`.
>>> is_counter(Counter[str])
True
>>> is_counter(Counter)
True
>>> is_counter(dict[str, int])
False
"""
try:
return issubclass(get_origin(typ), Counter) # type: ignore
except TypeError:
return typ is Counter
@cache
def is_bare_counter(typ: type[Any]) -> bool:
"""
Test if the type is `collections.Counter` without type args.
>>> is_bare_counter(Counter[str])
False
>>> is_bare_counter(Counter)
True
"""
origin = get_origin(typ)
if origin is Counter:
return not type_args(typ)
return typ is Counter
@cache
def is_none(typ: type[Any]) -> bool:
"""
>>> is_none(int)
False
>>> is_none(type(None))
True
>>> is_none(None)
False
"""
return typ is type(None) # noqa
PRIMITIVES = [int, float, bool, str]
@cache
def is_enum(typ: type[Any]) -> TypeGuard[enum.Enum]:
"""
Test if the type is `enum.Enum`.
"""
try:
return issubclass(typ, enum.Enum)
except TypeError:
return isinstance(typ, enum.Enum)
@cache
def is_primitive_subclass(typ: type[Any]) -> bool:
"""
Test if the type is a subclass of primitive type.
>>> is_primitive_subclass(str)
False
>>> class Str(str):
... pass
>>> is_primitive_subclass(Str)
True
"""
return is_primitive(typ) and typ not in PRIMITIVES and not is_new_type_primitive(typ)
@cache
def is_primitive(typ: type[Any] | NewType) -> bool:
"""
Test if the type is primitive.
>>> is_primitive(int)
True
>>> class CustomInt(int):
... pass
>>> is_primitive(CustomInt)
True
"""
try:
return any(issubclass(typ, ty) for ty in PRIMITIVES) # type: ignore
except TypeError:
return is_new_type_primitive(typ)
@cache
def is_new_type_primitive(typ: type[Any] | NewType) -> bool:
"""
Test if the type is a NewType of primitives.
"""
inner = getattr(typ, "__supertype__", None)
if inner:
return is_primitive(inner)
else:
return any(isinstance(typ, ty) for ty in PRIMITIVES)
@cache
def has_generic_base(typ: Any) -> bool:
return Generic in getattr(typ, "__mro__", ()) or Generic in getattr(typ, "__bases__", ())
@cache
def is_generic(typ: Any) -> bool:
"""
Test if the type is derived from `typing.Generic`.
>>> T = typing.TypeVar('T')
>>> class GenericFoo(typing.Generic[T]):
... pass
>>> is_generic(GenericFoo[int])
True
>>> is_generic(GenericFoo)
False
"""
origin = get_origin(typ)
return origin is not None and has_generic_base(origin)