-
-
Notifications
You must be signed in to change notification settings - Fork 113
/
converters.py
792 lines (685 loc) · 27.1 KB
/
converters.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
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
from collections import Counter
from collections.abc import MutableSet as AbcMutableSet
from dataclasses import Field
from enum import Enum
from functools import lru_cache
from typing import Any, Callable, Dict, Optional, Tuple, Type, TypeVar, Union
from attr import Attribute
from attr import has as attrs_has
from attr import resolve_types
from ._compat import (
FrozenSetSubscriptable,
Mapping,
MutableMapping,
MutableSequence,
MutableSet,
Sequence,
Set,
fields,
get_origin,
has,
has_with_generic,
is_annotated,
is_bare,
is_counter,
is_frozenset,
is_generic,
is_generic_attrs,
is_hetero_tuple,
is_literal,
is_mapping,
is_mutable_set,
is_protocol,
is_sequence,
is_tuple,
is_union_type,
)
from .disambiguators import create_uniq_field_dis_func
from .dispatch import MultiStrategyDispatch
from .errors import StructureHandlerNotFoundError
from .gen import (
AttributeOverride,
make_dict_structure_fn,
make_dict_unstructure_fn,
make_hetero_tuple_unstructure_fn,
make_iterable_unstructure_fn,
make_mapping_structure_fn,
make_mapping_unstructure_fn,
)
NoneType = type(None)
T = TypeVar("T")
V = TypeVar("V")
class UnstructureStrategy(Enum):
"""`attrs` classes unstructuring strategies."""
AS_DICT = "asdict"
AS_TUPLE = "astuple"
def _subclass(typ):
"""a shortcut"""
return lambda cls: issubclass(cls, typ)
def is_attrs_union(typ):
return is_union_type(typ) and all(
has(get_origin(e) or e) for e in typ.__args__
)
def is_attrs_union_or_none(typ):
return is_union_type(typ) and all(
e is NoneType or has(get_origin(e) or e) for e in typ.__args__
)
def is_optional(typ):
return (
is_union_type(typ)
and NoneType in typ.__args__
and len(typ.__args__) == 2
)
class Converter(object):
"""Converts between structured and unstructured data."""
__slots__ = (
"_dis_func_cache",
"_unstructure_func",
"_unstructure_attrs",
"_structure_attrs",
"_dict_factory",
"_union_struct_registry",
"_structure_func",
"_prefer_attrib_converters",
)
def __init__(
self,
dict_factory: Callable[[], Any] = dict,
unstruct_strat: UnstructureStrategy = UnstructureStrategy.AS_DICT,
prefer_attrib_converters: bool = False,
) -> None:
unstruct_strat = UnstructureStrategy(unstruct_strat)
self._prefer_attrib_converters = prefer_attrib_converters
# Create a per-instance cache.
if unstruct_strat is UnstructureStrategy.AS_DICT:
self._unstructure_attrs = self.unstructure_attrs_asdict
self._structure_attrs = self.structure_attrs_fromdict
else:
self._unstructure_attrs = self.unstructure_attrs_astuple
self._structure_attrs = self.structure_attrs_fromtuple
self._dis_func_cache = lru_cache()(self._get_dis_func)
self._unstructure_func = MultiStrategyDispatch(
self._unstructure_identity
)
self._unstructure_func.register_cls_list(
[
(bytes, self._unstructure_identity),
(str, self._unstructure_identity),
]
)
self._unstructure_func.register_func_list(
[
(
is_protocol,
lambda o: self.unstructure(o, unstructure_as=o.__class__),
),
(is_mapping, self._unstructure_mapping),
(is_sequence, self._unstructure_seq),
(is_mutable_set, self._unstructure_seq),
(is_frozenset, self._unstructure_seq),
(_subclass(Enum), self._unstructure_enum),
(has, self._unstructure_attrs),
(is_union_type, self._unstructure_union),
]
)
# Per-instance register of to-attrs converters.
# Singledispatch dispatches based on the first argument, so we
# store the function and switch the arguments in self.loads.
self._structure_func = MultiStrategyDispatch(self._structure_error)
self._structure_func.register_func_list(
[
(
lambda cl: cl is Any or cl is Optional or cl is None,
lambda v, _: v,
),
(is_generic_attrs, self._gen_structure_generic, True),
(is_literal, self._structure_literal),
(is_sequence, self._structure_list),
(is_mutable_set, self._structure_set),
(is_frozenset, self._structure_frozenset),
(is_tuple, self._structure_tuple),
(is_mapping, self._structure_dict),
(
is_attrs_union_or_none,
self._gen_attrs_union_structure,
True,
),
(
lambda t: is_union_type(t)
and t in self._union_struct_registry,
self._structure_union,
),
(is_optional, self._structure_optional),
(has, self._structure_attrs),
]
)
# Strings are sequences.
self._structure_func.register_cls_list(
[
(str, self._structure_call),
(bytes, self._structure_call),
(int, self._structure_call),
(float, self._structure_call),
(Enum, self._structure_call),
]
)
self._dict_factory = dict_factory
# Unions are instances now, not classes. We use different registries.
self._union_struct_registry: Dict[
Any, Callable[[Any, Type[T]], T]
] = {}
def unstructure(self, obj: Any, unstructure_as=None) -> Any:
return self._unstructure_func.dispatch(
obj.__class__ if unstructure_as is None else unstructure_as
)(obj)
@property
def unstruct_strat(self) -> UnstructureStrategy:
"""The default way of unstructuring ``attrs`` classes."""
return (
UnstructureStrategy.AS_DICT
if self._unstructure_attrs == self.unstructure_attrs_asdict
else UnstructureStrategy.AS_TUPLE
)
def register_unstructure_hook(
self, cls: Any, func: Callable[[T], Any]
) -> None:
"""Register a class-to-primitive converter function for a class.
The converter function should take an instance of the class and return
its Python equivalent.
"""
if attrs_has(cls):
resolve_types(cls)
if is_union_type(cls):
self._unstructure_func.register_func_list(
[(lambda t: t == cls, func)]
)
else:
self._unstructure_func.register_cls_list([(cls, func)])
def register_unstructure_hook_func(
self, check_func: Callable[[Any], bool], func: Callable[[T], Any]
):
"""Register a class-to-primitive converter function for a class, using
a function to check if it's a match.
"""
self._unstructure_func.register_func_list([(check_func, func)])
def register_unstructure_hook_factory(
self,
predicate: Callable[[Any], bool],
factory: Callable[[Any], Callable[[Any], Any]],
) -> None:
"""
Register a hook factory for a given predicate.
A predicate is a function that, given a type, returns whether the factory
can produce a hook for that type.
A factory is a callable that, given a type, produces an unstructuring
hook for that type. This unstructuring hook will be cached.
"""
self._unstructure_func.register_func_list([(predicate, factory, True)])
def register_structure_hook(
self, cl: Any, func: Callable[[Any, Type[T]], T]
):
"""Register a primitive-to-class converter function for a type.
The converter function should take two arguments:
* a Python object to be converted,
* the type to convert to
and return the instance of the class. The type may seem redundant, but
is sometimes needed (for example, when dealing with generic classes).
"""
if attrs_has(cl):
resolve_types(cl)
if is_union_type(cl):
self._union_struct_registry[cl] = func
self._structure_func.clear_cache()
else:
self._structure_func.register_cls_list([(cl, func)])
def register_structure_hook_func(
self,
check_func: Callable[[Type[T]], bool],
func: Callable[[Any, Type[T]], T],
):
"""Register a class-to-primitive converter function for a class, using
a function to check if it's a match.
"""
self._structure_func.register_func_list([(check_func, func)])
def register_structure_hook_factory(
self,
predicate: Callable[[Any], bool],
factory: Callable[[Any], Callable[[Any], Any]],
) -> None:
"""
Register a hook factory for a given predicate.
A predicate is a function that, given a type, returns whether the factory
can produce a hook for that type.
A factory is a callable that, given a type, produces a structuring
hook for that type. This structuring hook will be cached.
"""
self._structure_func.register_func_list([(predicate, factory, True)])
def structure(self, obj: Any, cl: Type[T]) -> T:
"""Convert unstructured Python data structures to structured data."""
return self._structure_func.dispatch(cl)(obj, cl)
# Classes to Python primitives.
def unstructure_attrs_asdict(self, obj) -> Dict[str, Any]:
"""Our version of `attrs.asdict`, so we can call back to us."""
attrs = fields(obj.__class__)
dispatch = self._unstructure_func.dispatch
rv = self._dict_factory()
for a in attrs:
name = a.name
v = getattr(obj, name)
rv[name] = dispatch(a.type or v.__class__)(v)
return rv
def unstructure_attrs_astuple(self, obj) -> Tuple[Any, ...]:
"""Our version of `attrs.astuple`, so we can call back to us."""
attrs = fields(obj.__class__)
dispatch = self._unstructure_func.dispatch
res = list()
for a in attrs:
name = a.name
v = getattr(obj, name)
res.append(dispatch(a.type or v.__class__)(v))
return tuple(res)
def _unstructure_enum(self, obj):
"""Convert an enum to its value."""
return obj.value
def _unstructure_identity(self, obj):
"""Just pass it through."""
return obj
def _unstructure_seq(self, seq):
"""Convert a sequence to primitive equivalents."""
# We can reuse the sequence class, so tuples stay tuples.
dispatch = self._unstructure_func.dispatch
return seq.__class__(dispatch(e.__class__)(e) for e in seq)
def _unstructure_mapping(self, mapping):
"""Convert a mapping of attr classes to primitive equivalents."""
# We can reuse the mapping class, so dicts stay dicts and OrderedDicts
# stay OrderedDicts.
dispatch = self._unstructure_func.dispatch
return mapping.__class__(
(dispatch(k.__class__)(k), dispatch(v.__class__)(v))
for k, v in mapping.items()
)
def _unstructure_union(self, obj):
"""
Unstructure an object as a union.
By default, just unstructures the instance.
"""
return self._unstructure_func.dispatch(obj.__class__)(obj)
# Python primitives to classes.
def _structure_error(self, _, cl):
"""At the bottom of the condition stack, we explode if we can't handle it."""
msg = (
"Unsupported type: {0!r}. Register a structure hook for "
"it.".format(cl)
)
raise StructureHandlerNotFoundError(msg, type_=cl)
def _gen_structure_generic(self, cl):
"""Create and return a hook for structuring generics."""
fn = make_dict_structure_fn(
cl,
self,
_cattrs_prefer_attrib_converters=self._prefer_attrib_converters,
)
return fn
def _gen_attrs_union_structure(self, cl):
"""Generate a structuring function for a union of attrs classes (and maybe None)."""
dis_fn = self._get_dis_func(cl)
has_none = NoneType in cl.__args__
if has_none:
def structure_attrs_union(obj, _):
if obj is None:
return None
return self.structure(obj, dis_fn(obj))
else:
def structure_attrs_union(obj, _):
return self.structure(obj, dis_fn(obj))
return structure_attrs_union
@staticmethod
def _structure_call(obj, cl):
"""Just call ``cl`` with the given ``obj``.
This is just an optimization on the ``_structure_default`` case, when
we know we can skip the ``if`` s. Use for ``str``, ``bytes``, ``enum``,
etc.
"""
return cl(obj)
@staticmethod
def _structure_literal(val, type):
if val not in type.__args__:
raise Exception(f"{val} not in literal {type}")
return val
# Attrs classes.
def structure_attrs_fromtuple(
self, obj: Tuple[Any, ...], cl: Type[T]
) -> T:
"""Load an attrs class from a sequence (tuple)."""
conv_obj = [] # A list of converter parameters.
for a, value in zip(fields(cl), obj): # type: ignore
# We detect the type by the metadata.
converted = self._structure_attribute(a, value)
conv_obj.append(converted)
return cl(*conv_obj) # type: ignore
def _structure_attribute(
self, a: Union[Attribute, Field], value: Any
) -> Any:
"""Handle an individual attrs attribute."""
type_ = a.type
attrib_converter = getattr(a, "converter", None)
if self._prefer_attrib_converters and attrib_converter:
# A attrib converter is defined on this attribute, and prefer_attrib_converters is set
# to give these priority over registered structure hooks. So, pass through the raw
# value, which attrs will flow into the converter
return value
if type_ is None:
# No type metadata.
return value
try:
return self._structure_func.dispatch(type_)(value, type_)
except StructureHandlerNotFoundError:
if attrib_converter:
# Return the original value and fallback to using an attrib converter.
return value
else:
raise
def structure_attrs_fromdict(
self, obj: Mapping[str, Any], cl: Type[T]
) -> T:
"""Instantiate an attrs class from a mapping (dict)."""
# For public use.
conv_obj = {} # Start with a fresh dict, to ignore extra keys.
for a in fields(cl): # type: ignore
name = a.name
try:
val = obj[name]
except KeyError:
continue
if name[0] == "_":
name = name[1:]
conv_obj[name] = self._structure_attribute(a, val)
return cl(**conv_obj) # type: ignore
def _structure_list(self, obj, cl):
"""Convert an iterable to a potentially generic list."""
if is_bare(cl) or cl.__args__[0] is Any:
return [e for e in obj]
else:
elem_type = cl.__args__[0]
return [
self._structure_func.dispatch(elem_type)(e, elem_type)
for e in obj
]
def _structure_set(self, obj, cl):
"""Convert an iterable into a potentially generic set."""
if is_bare(cl) or cl.__args__[0] is Any:
return set(obj)
else:
elem_type = cl.__args__[0]
return {
self._structure_func.dispatch(elem_type)(e, elem_type)
for e in obj
}
def _structure_frozenset(self, obj, cl):
"""Convert an iterable into a potentially generic frozenset."""
if is_bare(cl) or cl.__args__[0] is Any:
return frozenset(obj)
else:
elem_type = cl.__args__[0]
dispatch = self._structure_func.dispatch
return frozenset(dispatch(elem_type)(e, elem_type) for e in obj)
def _structure_dict(self, obj, cl):
"""Convert a mapping into a potentially generic dict."""
if is_bare(cl) or cl.__args__ == (Any, Any):
return dict(obj)
else:
key_type, val_type = cl.__args__
if key_type is Any:
val_conv = self._structure_func.dispatch(val_type)
return {k: val_conv(v, val_type) for k, v in obj.items()}
elif val_type is Any:
key_conv = self._structure_func.dispatch(key_type)
return {key_conv(k, key_type): v for k, v in obj.items()}
else:
key_conv = self._structure_func.dispatch(key_type)
val_conv = self._structure_func.dispatch(val_type)
return {
key_conv(k, key_type): val_conv(v, val_type)
for k, v in obj.items()
}
def _structure_optional(self, obj, union):
if obj is None:
return None
union_params = union.__args__
other = (
union_params[0] if union_params[1] is NoneType else union_params[1]
)
# We can't actually have a Union of a Union, so this is safe.
return self._structure_func.dispatch(other)(obj, other)
def _structure_union(self, obj, union):
"""Deal with structuring a union."""
handler = self._union_struct_registry[union]
return handler(obj, union)
def _structure_tuple(self, obj, tup: Type[T]):
"""Deal with converting to a tuple."""
if tup in (Tuple, tuple):
tup_params = None
else:
tup_params = tup.__args__
has_ellipsis = tup_params and tup_params[-1] is Ellipsis
if tup_params is None or (has_ellipsis and tup_params[0] is Any):
# Just a Tuple. (No generic information.)
return tuple(obj)
if has_ellipsis:
# We're dealing with a homogenous tuple, Tuple[int, ...]
tup_type = tup_params[0]
conv = self._structure_func.dispatch(tup_type)
return tuple(conv(e, tup_type) for e in obj)
else:
# We're dealing with a heterogenous tuple.
return tuple(
self._structure_func.dispatch(t)(e, t)
for t, e in zip(tup_params, obj)
)
@staticmethod
def _get_dis_func(union):
# type: (Type) -> Callable[..., Type]
"""Fetch or try creating a disambiguation function for a union."""
union_types = union.__args__
if NoneType in union_types: # type: ignore
# We support unions of attrs classes and NoneType higher in the
# logic.
union_types = tuple(
e for e in union_types if e is not NoneType # type: ignore
)
if not all(has(get_origin(e) or e) for e in union_types):
raise StructureHandlerNotFoundError(
"Only unions of attrs classes supported "
"currently. Register a loads hook manually.",
type_=union,
)
return create_uniq_field_dis_func(*union_types)
class GenConverter(Converter):
"""A converter which generates specialized un/structuring functions."""
__slots__ = (
"omit_if_default",
"forbid_extra_keys",
"type_overrides",
"_unstruct_collection_overrides",
)
def __init__(
self,
dict_factory: Callable[[], Any] = dict,
unstruct_strat: UnstructureStrategy = UnstructureStrategy.AS_DICT,
omit_if_default: bool = False,
forbid_extra_keys: bool = False,
type_overrides: Mapping[Type, AttributeOverride] = {},
unstruct_collection_overrides: Mapping[Type, Callable] = {},
prefer_attrib_converters: bool = False,
):
super().__init__(
dict_factory=dict_factory,
unstruct_strat=unstruct_strat,
prefer_attrib_converters=prefer_attrib_converters,
)
self.omit_if_default = omit_if_default
self.forbid_extra_keys = forbid_extra_keys
self.type_overrides = dict(type_overrides)
self._unstruct_collection_overrides = unstruct_collection_overrides
# Do a little post-processing magic to make things easier for users.
co = unstruct_collection_overrides
# abc.Set overrides, if defined, apply to abc.MutableSets and sets
if Set in co:
if MutableSet not in co:
co[MutableSet] = co[Set]
co[AbcMutableSet] = co[Set] # For 3.7/3.8 compatibility.
if FrozenSetSubscriptable not in co:
co[FrozenSetSubscriptable] = co[Set]
# abc.MutableSet overrrides, if defined, apply to sets
if MutableSet in co:
if set not in co:
co[set] = co[MutableSet]
if FrozenSetSubscriptable in co:
co[frozenset] = co[
FrozenSetSubscriptable
] # For 3.7/3.8 compatibility.
# abc.Sequence overrides, if defined, can apply to MutableSequences, lists and tuples
if Sequence in co:
if MutableSequence not in co:
co[MutableSequence] = co[Sequence]
if tuple not in co:
co[tuple] = co[Sequence]
# abc.MutableSequence overrides, if defined, can apply to lists
if MutableSequence in co:
if list not in co:
co[list] = co[MutableSequence]
# abc.Mapping overrides, if defined, can apply to MutableMappings
if Mapping in co:
if MutableMapping not in co:
co[MutableMapping] = co[Mapping]
# abc.MutableMapping overrides, if defined, can apply to dicts
if MutableMapping in co:
if dict not in co:
co[dict] = co[MutableMapping]
# builtins.dict overrides, if defined, can apply to counters
if dict in co:
if Counter not in co:
co[Counter] = co[dict]
if unstruct_strat is UnstructureStrategy.AS_DICT:
# Override the attrs handler.
self.register_unstructure_hook_factory(
has_with_generic, self.gen_unstructure_attrs_fromdict
)
self.register_structure_hook_factory(
has_with_generic, self.gen_structure_attrs_fromdict
)
self.register_unstructure_hook_factory(
is_annotated, self.gen_unstructure_annotated
)
self.register_unstructure_hook_factory(
is_hetero_tuple, self.gen_unstructure_hetero_tuple
)
self.register_unstructure_hook_factory(
is_sequence, self.gen_unstructure_iterable
)
self.register_unstructure_hook_factory(
is_mapping, self.gen_unstructure_mapping
)
self.register_unstructure_hook_factory(
is_mutable_set,
lambda cl: self.gen_unstructure_iterable(cl, unstructure_to=set),
)
self.register_unstructure_hook_factory(
is_frozenset,
lambda cl: self.gen_unstructure_iterable(
cl, unstructure_to=frozenset
),
)
self.register_structure_hook_factory(
is_annotated, self.gen_structure_annotated
)
self.register_structure_hook_factory(
is_mapping, self.gen_structure_mapping
)
self.register_structure_hook_factory(
is_counter, self.gen_structure_counter
)
def gen_unstructure_annotated(self, type):
origin = type.__origin__
h = self._unstructure_func.dispatch(origin)
return h
def gen_structure_annotated(self, type):
origin = type.__origin__
h = self._structure_func.dispatch(origin)
return h
def gen_unstructure_attrs_fromdict(self, cl: Type[T]) -> Dict[str, Any]:
origin = get_origin(cl)
attribs = fields(origin or cl)
if attrs_has(cl) and any(isinstance(a.type, str) for a in attribs):
# PEP 563 annotations - need to be resolved.
resolve_types(cl)
attrib_overrides = {
a.name: self.type_overrides[a.type]
for a in attribs
if a.type in self.type_overrides
}
h = make_dict_unstructure_fn(
cl,
self,
_cattrs_omit_if_default=self.omit_if_default,
**attrib_overrides,
)
return h
def gen_structure_attrs_fromdict(self, cl: Type[T]) -> T:
attribs = fields(get_origin(cl) if is_generic(cl) else cl)
if attrs_has(cl) and any(isinstance(a.type, str) for a in attribs):
# PEP 563 annotations - need to be resolved.
resolve_types(cl)
attrib_overrides = {
a.name: self.type_overrides[a.type]
for a in attribs
if a.type in self.type_overrides
}
h = make_dict_structure_fn(
cl,
self,
_cattrs_forbid_extra_keys=self.forbid_extra_keys,
_cattrs_prefer_attrib_converters=self._prefer_attrib_converters,
**attrib_overrides,
)
# only direct dispatch so that subclasses get separately generated
return h
def gen_unstructure_iterable(self, cl: Any, unstructure_to=None):
unstructure_to = self._unstruct_collection_overrides.get(
get_origin(cl) or cl, unstructure_to or list
)
h = make_iterable_unstructure_fn(
cl, self, unstructure_to=unstructure_to
)
self._unstructure_func.register_cls_list([(cl, h)], direct=True)
return h
def gen_unstructure_hetero_tuple(self, cl: Any, unstructure_to=None):
unstructure_to = self._unstruct_collection_overrides.get(
get_origin(cl) or cl, unstructure_to or tuple
)
h = make_hetero_tuple_unstructure_fn(
cl, self, unstructure_to=unstructure_to
)
self._unstructure_func.register_cls_list([(cl, h)], direct=True)
return h
def gen_unstructure_mapping(
self, cl: Any, unstructure_to=None, key_handler=None
):
unstructure_to = self._unstruct_collection_overrides.get(
get_origin(cl) or cl, unstructure_to or dict
)
h = make_mapping_unstructure_fn(
cl, self, unstructure_to=unstructure_to, key_handler=key_handler
)
self._unstructure_func.register_cls_list([(cl, h)], direct=True)
return h
def gen_structure_counter(self, cl: Any):
h = make_mapping_structure_fn(
cl, self, structure_to=Counter, val_type=int
)
self._structure_func.register_cls_list([(cl, h)], direct=True)
return h
def gen_structure_mapping(self, cl: Any):
h = make_mapping_structure_fn(cl, self)
self._structure_func.register_cls_list([(cl, h)], direct=True)
return h