-
-
Notifications
You must be signed in to change notification settings - Fork 113
/
_compat.py
375 lines (315 loc) · 10.7 KB
/
_compat.py
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
import sys
from dataclasses import MISSING
from dataclasses import fields as dataclass_fields
from dataclasses import is_dataclass
from typing import Any, Dict, FrozenSet, List
from typing import Mapping as TypingMapping
from typing import MutableMapping as TypingMutableMapping
from typing import MutableSequence as TypingMutableSequence
from typing import MutableSet as TypingMutableSet
from typing import Sequence as TypingSequence
from typing import Set as TypingSet
from typing import Tuple, get_type_hints
from attr import NOTHING, Attribute, Factory
from attr import fields as attrs_fields
from attr import resolve_types
version_info = sys.version_info[0:3]
is_py37 = version_info[:2] == (3, 7)
is_py38 = version_info[:2] == (3, 8)
is_py39_plus = version_info[:2] >= (3, 9)
is_py310_plus = version_info[:2] >= (3, 10)
if is_py37:
def get_args(cl):
return cl.__args__
def get_origin(cl):
return getattr(cl, "__origin__", None)
from typing_extensions import Protocol
else:
from typing import Protocol, get_args, get_origin # NOQA
def has(cls):
return hasattr(cls, "__attrs_attrs__") or hasattr(
cls, "__dataclass_fields__"
)
def has_with_generic(cls):
"""Test whether the class if a normal or generic attrs or dataclass."""
return has(cls) or has(get_origin(cls))
def fields(type):
try:
return type.__attrs_attrs__
except AttributeError:
try:
return dataclass_fields(type)
except AttributeError:
raise Exception("Not an attrs or dataclass class.")
def adapted_fields(cl) -> List[Attribute]:
"""Return the attrs format of `fields()` for attrs and dataclasses."""
if is_dataclass(cl):
attrs = dataclass_fields(cl)
if any(isinstance(a.type, str) for a in attrs):
# Do this conditionally in case `get_type_hints` fails, so
# users can resolve on their own first.
type_hints = get_type_hints(cl)
else:
type_hints = {}
return [
Attribute(
attr.name,
attr.default
if attr.default is not MISSING
else (
Factory(attr.default_factory)
if attr.default_factory is not MISSING
else NOTHING
),
None,
True,
None,
True,
attr.init,
True,
type=type_hints.get(attr.name, attr.type),
)
for attr in attrs
]
else:
attribs = attrs_fields(cl)
if any(isinstance(a.type, str) for a in attribs):
# PEP 563 annotations - need to be resolved.
resolve_types(cl)
attribs = attrs_fields(cl)
return attribs
def is_hetero_tuple(type: Any) -> bool:
origin = getattr(type, "__origin__", None)
return origin is tuple and ... not in type.__args__
def is_protocol(type: Any) -> bool:
return issubclass(type, Protocol) and getattr(type, "_is_protocol", False)
if is_py37 or is_py38:
Set = TypingSet
MutableSet = TypingMutableSet
Sequence = TypingSequence
MutableSequence = TypingMutableSequence
MutableMapping = TypingMutableMapping
Mapping = TypingMapping
FrozenSetSubscriptable = FrozenSet
TupleSubscriptable = Tuple
from collections import Counter as ColCounter
from typing import Counter, Union, _GenericAlias
def is_annotated(_):
return False
def is_tuple(type):
return type in (Tuple, tuple) or (
type.__class__ is _GenericAlias
and issubclass(type.__origin__, Tuple)
)
def is_union_type(obj):
return (
obj is Union
or isinstance(obj, _GenericAlias)
and obj.__origin__ is Union
)
def is_sequence(type: Any) -> bool:
return type in (List, list, Tuple, tuple) or (
type.__class__ is _GenericAlias
and (
type.__origin__ not in (Union, Tuple, tuple)
and issubclass(type.__origin__, TypingSequence)
)
or (type.__origin__ in (Tuple, tuple) and type.__args__[1] is ...)
)
def is_mutable_set(type):
return type is set or (
type.__class__ is _GenericAlias
and issubclass(type.__origin__, MutableSet)
)
def is_frozenset(type):
return type is frozenset or (
type.__class__ is _GenericAlias
and issubclass(type.__origin__, FrozenSet)
)
def is_mapping(type):
return type in (TypingMapping, dict) or (
type.__class__ is _GenericAlias
and issubclass(type.__origin__, TypingMapping)
)
bare_list_args = List.__args__
bare_seq_args = TypingSequence.__args__
bare_mapping_args = TypingMapping.__args__
bare_dict_args = Dict.__args__
bare_mutable_seq_args = TypingMutableSequence.__args__
def is_bare(type):
args = type.__args__
return (
args == bare_list_args
or args == bare_seq_args
or args == bare_mapping_args
or args == bare_dict_args
or args == bare_mutable_seq_args
)
def is_counter(type):
return (
type in (Counter, ColCounter)
or getattr(type, "__origin__", None) is ColCounter
)
if is_py38:
from typing import Literal
def is_literal(type) -> bool:
return (
type.__class__ is _GenericAlias and type.__origin__ is Literal
)
else:
# No literals in 3.7.
def is_literal(_) -> bool:
return False
def is_generic(obj):
return isinstance(obj, _GenericAlias)
def copy_with(type, args):
"""Replace a generic type's arguments."""
return type.copy_with(args)
else:
# 3.9+
from collections import Counter
from collections.abc import Mapping as AbcMapping
from collections.abc import MutableMapping as AbcMutableMapping
from collections.abc import MutableSequence as AbcMutableSequence
from collections.abc import MutableSet as AbcMutableSet
from collections.abc import Sequence as AbcSequence
from collections.abc import Set as AbcSet
from types import GenericAlias
from typing import Annotated
from typing import Counter as TypingCounter
from typing import (
Union,
_AnnotatedAlias,
_GenericAlias,
_SpecialGenericAlias,
_UnionGenericAlias,
)
try:
# Not present on 3.9.0, so we try carefully.
from typing import _LiteralGenericAlias
def is_literal(type) -> bool:
return type.__class__ is _LiteralGenericAlias
except ImportError:
def is_literal(_) -> bool:
return False
Set = AbcSet
MutableSet = AbcMutableSet
Sequence = AbcSequence
MutableSequence = AbcMutableSequence
MutableMapping = AbcMutableMapping
Mapping = AbcMapping
FrozenSetSubscriptable = frozenset
TupleSubscriptable = tuple
def is_annotated(type) -> bool:
return getattr(type, "__class__", None) is _AnnotatedAlias
def is_tuple(type):
return (
type in (Tuple, tuple)
or (
type.__class__ is _GenericAlias
and issubclass(type.__origin__, Tuple)
)
or (getattr(type, "__origin__", None) is tuple)
)
if is_py310_plus:
def is_union_type(obj):
from types import UnionType
return (
obj is Union
or (
isinstance(obj, _UnionGenericAlias)
and obj.__origin__ is Union
)
or isinstance(obj, UnionType)
)
else:
def is_union_type(obj):
return (
obj is Union
or isinstance(obj, _UnionGenericAlias)
and obj.__origin__ is Union
)
def is_sequence(type: Any) -> bool:
origin = getattr(type, "__origin__", None)
return (
type
in (
List,
list,
TypingSequence,
TypingMutableSequence,
AbcMutableSequence,
tuple,
)
or (
type.__class__ is _GenericAlias
and (
(origin is not tuple)
and issubclass(origin, TypingSequence)
or origin is tuple
and type.__args__[1] is ...
)
)
or (origin in (list, AbcMutableSequence, AbcSequence))
or (origin is tuple and type.__args__[1] is ...)
)
def is_mutable_set(type):
return (
type in (TypingSet, TypingMutableSet, set)
or (
type.__class__ is _GenericAlias
and issubclass(type.__origin__, TypingMutableSet)
)
or (
getattr(type, "__origin__", None)
in (set, AbcMutableSet, AbcSet)
)
)
def is_frozenset(type):
return (
type in (FrozenSet, frozenset)
or (
type.__class__ is _GenericAlias
and issubclass(type.__origin__, FrozenSet)
)
or (getattr(type, "__origin__", None) is frozenset)
)
def is_bare(type):
return isinstance(type, _SpecialGenericAlias) or (
not hasattr(type, "__origin__") and not hasattr(type, "__args__")
)
def is_mapping(type):
return (
type
in (
TypingMapping,
Dict,
TypingMutableMapping,
dict,
AbcMutableMapping,
)
or (
type.__class__ is _GenericAlias
and issubclass(type.__origin__, TypingMapping)
)
or (
getattr(type, "__origin__", None)
in (dict, AbcMutableMapping, AbcMapping)
)
or issubclass(type, dict)
)
def is_counter(type):
return (
type in (Counter, TypingCounter)
or getattr(type, "__origin__", None) is Counter
)
def is_generic(obj):
return isinstance(obj, _GenericAlias) or isinstance(obj, GenericAlias)
def copy_with(type, args):
"""Replace a generic type's arguments."""
if is_annotated(type):
# typing.Annotated requires a special case.
return Annotated[args] # type: ignore
return type.__origin__[args]
def is_generic_attrs(type):
return is_generic(type) and has(type.__origin__)