-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathde.py
More file actions
1563 lines (1366 loc) · 50.5 KB
/
Copy pathde.py
File metadata and controls
1563 lines (1366 loc) · 50.5 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
"""
This module provides `deserialize`, `is_deserializable` `from_dict`, `from_tuple` and classes
and functions associated with deserialization.
"""
from __future__ import annotations
import abc
import itertools
import collections
import dataclasses
import functools
import typing
import jinja2
from collections.abc import Callable, Sequence, Iterable
from beartype import beartype, BeartypeConf
from beartype.door import is_bearable
from beartype.roar import BeartypeCallHintParamViolation
from dataclasses import dataclass, is_dataclass
from typing import Any, Generic, Iterator, Literal, TypeVar, cast, overload
from typing_extensions import dataclass_transform
from .compat import (
SerdeError,
SerdeSkip,
T,
UserError,
find_generic_arg,
get_args,
get_generic_arg,
get_origin,
get_type_var_names,
is_any,
is_bare_counter,
is_bare_deque,
is_bare_dict,
is_bare_list,
is_bare_set,
is_bare_tuple,
is_counter,
is_datetime,
is_default_dict,
is_deque,
is_dict,
is_ellipsis,
is_enum,
is_flatten_dict,
is_frozen_set,
is_generic,
is_list,
is_literal,
is_none,
is_opt,
is_primitive,
is_primitive_subclass,
is_set,
is_str_serializable,
is_tuple,
is_union,
is_variable_tuple,
is_pep695_type_alias,
iter_literals,
iter_types,
iter_unions,
type_args,
typename,
)
from .core import (
GLOBAL_CLASS_DESERIALIZER,
ClassDeserializer,
FROM_DICT,
FROM_ITER,
SERDE_SCOPE,
CACHE,
UNION_DE_PREFIX,
DefaultTagging,
Field,
disabled,
Scope,
Tagging,
TypeCheck,
add_func,
coerce_object,
strict,
get_transparent_field,
has_default,
has_default_factory,
ensure,
fields,
is_instance,
literal_func_name,
logger,
union_func_name,
)
# Lazy numpy imports to improve startup time
__all__ = ["deserialize", "is_deserializable", "from_dict", "from_tuple"]
# Lazy numpy import wrappers to improve startup time
def _is_numpy_array(typ: Any) -> bool:
from .numpy import is_numpy_array
return is_numpy_array(typ)
def _is_numpy_scalar(typ: Any) -> bool:
from .numpy import is_numpy_scalar
return is_numpy_scalar(typ)
def _is_numpy_jaxtyping(typ: Any) -> bool:
from .numpy import is_numpy_jaxtyping
return is_numpy_jaxtyping(typ)
DeserializeFunc = Callable[[type[Any], Any], Any]
""" Interface of Custom deserialize function. """
def serde_legacy_custom_class_deserializer(
cls: type[Any], datavar: Any, value: Any, custom: DeserializeFunc, default: Callable[[], Any]
) -> Any:
"""
Handle custom deserialization. Use default deserialization logic if it receives `SerdeSkip`
exception.
:param cls: Type of the field.
:param datavar: The whole variable to deserialize from. e.g. "data"
:param value: The value for the field. e.g. "data['i']"
:param custom: Custom deserialize function.
:param default: Default deserialize function.
"""
try:
return custom(cls, value)
except SerdeSkip:
return default()
def default_deserializer(_cls: type[Any], obj: Any) -> Any:
"""
Marker function to tell serde to use the default deserializer. It's used when custom
deserializer is specified at the class but you want to override a field with the default
deserializer.
"""
def _get_by_aliases(d: dict[str, str], aliases: list[str], raise_error: bool = True) -> str | None:
if not aliases:
if raise_error:
raise KeyError("Tried all aliases, but key not found")
else:
return None
if aliases[0] in d:
return d[aliases[0]]
else:
return _get_by_aliases(d, aliases[1:], raise_error=raise_error)
def _exists_by_aliases(d: dict[str, str], aliases: list[str]) -> bool:
for alias in aliases:
if alias in d:
return True
return False
def _make_deserialize(
cls_name: str,
fields: list[Any],
*args: Any,
rename_all: str | None = None,
reuse_instances_default: bool = True,
convert_sets_default: bool = False,
skip_if_default: bool = False,
skip_if_none: bool = False,
deserializer: DeserializeFunc | None = None,
type_check: TypeCheck = strict,
transparent: bool = False,
class_deserializer: ClassDeserializer | None = None,
**kwargs: Any,
) -> type[Any]:
"""
Create a deserializable class programatically.
"""
C: type[Any] = dataclasses.make_dataclass(cls_name, fields, *args, **kwargs)
C = deserialize(
C,
rename_all=rename_all,
reuse_instances_default=reuse_instances_default,
convert_sets_default=convert_sets_default,
skip_if_default=skip_if_default,
skip_if_none=skip_if_none,
transparent=transparent,
**kwargs,
)
return C
# The `deserialize` function can call itself recursively when it needs to generate code for
# unmarked dataclasses. To avoid infinite recursion, this array remembers types for which code is
# currently being generated.
GENERATION_STACK = []
@dataclass_transform()
def deserialize(
_cls: type[T] | None = None,
rename_all: str | None = None,
reuse_instances_default: bool = True,
convert_sets_default: bool = False,
skip_if_default: bool = False,
skip_if_none: bool = False,
deserializer: DeserializeFunc | None = None,
tagging: Tagging = DefaultTagging,
type_check: TypeCheck = strict,
class_deserializer: ClassDeserializer | None = None,
deny_unknown_fields: bool = False,
transparent: bool = False,
**kwargs: Any,
) -> type[T]:
"""
A dataclass with this decorator is deserializable from any of the data formats supported
by pyserde.
>>> from serde import deserialize
>>> from serde.json import from_json
>>>
>>> @deserialize
... class Foo:
... i: int
... s: str
... f: float
... b: bool
>>>
>>> from_json(Foo, '{"i": 10, "s": "foo", "f": 100.0, "b": true}')
Foo(i=10, s='foo', f=100.0, b=True)
"""
stack = []
def wrap(cls: type[T]) -> type[T]:
if cls in stack:
return cls
stack.append(cls)
tagging.check()
# If no `dataclass` found in the class, dataclassify it automatically.
if not is_dataclass(cls):
dataclass(cls)
if transparent:
get_transparent_field(cls)
if type_check.is_strict():
serde_beartype = beartype(conf=BeartypeConf(violation_type=SerdeError))
serde_beartype(cls)
g: dict[str, Any] = {}
# Create a scope storage used by serde.
# Each class should get own scope. Child classes can not share scope with parent class.
# That's why we need the "scope.cls is not cls" check.
scope: Scope | None = getattr(cls, SERDE_SCOPE, None)
if scope is None or scope.cls is not cls:
scope = Scope(
cls,
reuse_instances_default=reuse_instances_default,
convert_sets_default=convert_sets_default,
skip_if_default_default=skip_if_default,
skip_if_none_default=skip_if_none,
)
setattr(cls, SERDE_SCOPE, scope)
scope.transparent = transparent
class_deserializers: list[ClassDeserializer] = list(
itertools.chain(
GLOBAL_CLASS_DESERIALIZER, [class_deserializer] if class_deserializer else []
)
)
# Set some globals for all generated functions
g["cls"] = cls
g["serde_scope"] = scope
g["SerdeError"] = SerdeError
g["UserError"] = UserError
g["typename"] = typename
g["ensure"] = ensure
g["typing"] = typing
g["collections"] = collections
g["Literal"] = Literal
g["from_obj"] = from_obj
g["get_generic_arg"] = get_generic_arg
g["is_instance"] = is_instance
g["TypeCheck"] = TypeCheck
g["disabled"] = disabled
g["coerce_object"] = coerce_object
g["_exists_by_aliases"] = _exists_by_aliases
g["_get_by_aliases"] = _get_by_aliases
g["class_deserializers"] = class_deserializers
g["BeartypeCallHintParamViolation"] = BeartypeCallHintParamViolation
g["is_bearable"] = is_bearable
if deserializer:
g["serde_legacy_custom_class_deserializer"] = functools.partial(
serde_legacy_custom_class_deserializer, custom=deserializer
)
# Collect types used in the generated code.
for typ in iter_types(cls):
# When we encounter a dataclass not marked with deserialize, then also generate
# deserialize functions for it.
if is_dataclass_without_de(typ) and typ is not cls:
# We call deserialize and not wrap to make sure that we will use the default serde
# configuration for generating the deserialization function.
deserialize(typ)
# We don't want to add primitive class e.g "str" into the scope, but primitive
# compatible types such as IntEnum and a subclass of primitives are added,
# so that generated code can use those types.
if is_primitive(typ) and not is_enum(typ) and not is_primitive_subclass(typ):
continue
if is_generic(typ):
g[typename(typ)] = get_origin(typ)
else:
g[typename(typ)] = typ
# render all union functions
for union in iter_unions(cls):
union_args = type_args(union)
add_func(
scope,
union_func_name(UNION_DE_PREFIX, union_args),
render_union_func(cls, union_args, tagging),
g,
)
# render literal functions
for literal in iter_literals(cls):
literal_args = type_args(literal)
add_func(
scope, literal_func_name(literal_args), render_literal_func(cls, literal_args), g
)
# Collect default values and default factories used in the generated code.
for f in defields(cls):
assert f.name
if has_default(f):
scope.defaults[f.name] = f.default
elif has_default_factory(f):
scope.defaults[f.name] = f.default_factory
if f.deserializer:
g[f.deserializer.name] = f.deserializer
add_func(
scope,
FROM_ITER,
render_from_iter(cls, deserializer, type_check, class_deserializer=class_deserializer),
g,
)
add_func(
scope,
FROM_DICT,
render_from_dict(
cls,
rename_all,
deserializer,
type_check,
class_deserializer=class_deserializer,
deny_unknown_fields=deny_unknown_fields,
),
g,
)
logger.debug(f"{typename(cls)}: {SERDE_SCOPE} {scope}")
stack.pop()
return cls
if _cls is None:
return wrap # type: ignore
if _cls in GENERATION_STACK:
return _cls
GENERATION_STACK.append(_cls)
try:
return wrap(_cls)
finally:
GENERATION_STACK.pop()
def is_deserializable(instance_or_class: Any) -> bool:
"""
Test if an instance or class is deserializable.
>>> @deserialize
... class Foo:
... pass
>>>
>>> is_deserializable(Foo)
True
"""
return hasattr(instance_or_class, SERDE_SCOPE)
def is_dataclass_without_de(cls: type[Any]) -> bool:
if not dataclasses.is_dataclass(cls):
return False
if not hasattr(cls, SERDE_SCOPE):
return True
scope: Scope | None = getattr(cls, SERDE_SCOPE)
if not scope:
return True
return FROM_DICT not in scope.funcs
class Deserializer(Generic[T], metaclass=abc.ABCMeta):
"""
`Deserializer` base class. Subclass this to customize deserialize behaviour.
See `serde.json.JsonDeserializer` and `serde.msgpack.MsgPackDeserializer` for example usage.
"""
@classmethod
@abc.abstractmethod
def deserialize(cls, data: T, **opts: Any) -> Any:
"""
deserialize `data` into an object typically `dict`, `list` or `tuple`.
For example, `serde.json.JsonDeserializer` takes json string and deserialize
into an object. `serde.msgpack.MsgPackDeserializer` takes msgpack bytes and
deserialize into an object.
"""
raise NotImplementedError
def from_obj(
c: type[T],
o: Any,
named: bool,
reuse_instances: bool | None,
deserialize_numbers: Callable[[str | int], float] | None = None,
) -> T:
"""
Deserialize from an object into an instance of the type specified as arg `c`.
`c` can be either primitive type, `list`, `tuple`, `dict` or `deserialize` class.
* `deserialize_numbers`: Optional callable to coerce numeric input into float (and subclasses)
when a float target is encountered. Useful for callers that want to treat ints or strings as
floats.
"""
res: Any
# It is possible that the parser already generates the correct data type requested
# by the caller. Hence, it should be checked early to avoid doing anymore work.
if type(o) is c:
return o
def deserializable_to_obj(cls: type[T]) -> T:
serde_scope: Scope = getattr(cls, SERDE_SCOPE)
func_name = FROM_DICT if named else FROM_ITER
res = serde_scope.funcs[func_name](
cls,
maybe_generic=maybe_generic,
data=o,
reuse_instances=reuse_instances,
deserialize_numbers=deserialize_numbers,
)
return res # type: ignore
if is_union(c) and not is_opt(c):
# If a class in the argument is a non-dataclass class e.g. Union[Foo, Bar],
# pyserde generates a wrapper (de)serializable dataclass on the fly,
# and use it to deserialize into the object.
return CACHE.deserialize_union(c, o, deserialize_numbers=deserialize_numbers)
if is_generic(c):
# Store subscripted generic type such as Foo[Bar] in "maybe_generic",
# and store origin type such as Foo in "c". Since subscripted generics
# are not a subclass of "type", use "c" for type inspection, and pass
# "maybe_generic" in deserialize functions.
maybe_generic = c
c = get_origin(c) # type: ignore
else:
maybe_generic = c
try:
thisfunc = functools.partial(
from_obj,
named=named,
reuse_instances=reuse_instances,
deserialize_numbers=deserialize_numbers,
)
if is_dataclass_without_de(c):
# Do not automatically implement beartype if dataclass without serde decorator
# is passed, because it is surprising for users
# See https://github.com/yukinarit/pyserde/issues/480
deserialize(c, type_check=disabled)
res = deserializable_to_obj(c)
elif is_deserializable(c):
res = deserializable_to_obj(c)
elif is_opt(c):
if o is None:
res = None
else:
res = thisfunc(type_args(c)[0], o)
elif is_list(c):
if is_bare_list(c):
res = list(o)
else:
res = [thisfunc(type_args(c)[0], e) for e in o]
elif is_set(c):
if is_bare_set(c):
res = set(o)
elif is_frozen_set(c):
res = frozenset(thisfunc(type_args(c)[0], e) for e in o)
else:
res = {thisfunc(type_args(c)[0], e) for e in o}
elif is_deque(c):
if is_bare_deque(c):
res = collections.deque(o)
else:
res = collections.deque(thisfunc(type_args(c)[0], e) for e in o)
elif is_counter(c):
if is_bare_counter(c):
res = collections.Counter(o)
else:
res = collections.Counter({thisfunc(type_args(c)[0], k): v for k, v in o.items()})
elif is_tuple(c):
if is_bare_tuple(c) or is_variable_tuple(c):
res = tuple(e for e in o)
else:
res = tuple(thisfunc(type_args(c)[i], e) for i, e in enumerate(o))
elif is_dict(c):
if is_bare_dict(c):
res = o
elif is_default_dict(c):
f = DeField(c, "")
v = f.value_field()
origin = get_origin(v.type)
res = collections.defaultdict(
origin if origin else v.type,
{
thisfunc(type_args(c)[0], k): thisfunc(type_args(c)[1], v)
for k, v in o.items()
},
)
else:
res = {
thisfunc(type_args(c)[0], k): thisfunc(type_args(c)[1], v) for k, v in o.items()
}
elif _is_numpy_array(c):
from .numpy import deserialize_numpy_array_direct
res = deserialize_numpy_array_direct(c, o)
elif is_datetime(c):
res = c.fromisoformat(o)
elif isinstance(c, type) and issubclass(c, float):
res = deserialize_numbers(o) if deserialize_numbers else c(o)
elif is_any(c) or is_ellipsis(c):
res = o
else:
res = cast(Any, c)(o)
return cast(T, res)
except UserError as e:
raise e.inner from None
except Exception as e:
raise SerdeError(e) from None
@overload
def from_dict(
cls: type[T],
o: dict[str, Any],
reuse_instances: bool | None = None,
deserialize_numbers: Callable[[str | int], float] | None = None,
) -> T: ...
@overload
def from_dict(
cls: Any,
o: dict[str, Any],
reuse_instances: bool | None = None,
deserialize_numbers: Callable[[str | int], float] | None = None,
) -> Any: ...
def from_dict(
cls: Any,
o: dict[str, Any],
reuse_instances: bool | None = None,
deserialize_numbers: Callable[[str | int], float] | None = None,
) -> Any:
"""
Deserialize dictionary into object.
>>> @deserialize
... class Foo:
... i: int
... s: str = 'foo'
... f: float = 100.0
... b: bool = True
>>>
>>> from_dict(Foo, {'i': 10, 's': 'foo', 'f': 100.0, 'b': True})
Foo(i=10, s='foo', f=100.0, b=True)
You can pass any type supported by pyserde. For example,
* `deserialize_numbers`: Optional callable to coerce numeric input to floats when the target
type is float (e.g. accept ints or numeric strings supplied by a parser).
>>> lst = [{'i': 10, 's': 'foo', 'f': 100.0, 'b': True},
... {'i': 20, 's': 'foo', 'f': 100.0, 'b': True}]
>>> from_dict(list[Foo], lst)
[Foo(i=10, s='foo', f=100.0, b=True), Foo(i=20, s='foo', f=100.0, b=True)]
"""
return from_obj(
cls,
o,
named=True,
reuse_instances=reuse_instances,
deserialize_numbers=deserialize_numbers,
)
@overload
def from_tuple(
cls: type[T],
o: Any,
reuse_instances: bool | None = None,
deserialize_numbers: Callable[[str | int], float] | None = None,
) -> T: ...
@overload
def from_tuple(
cls: Any,
o: Any,
reuse_instances: bool | None = None,
deserialize_numbers: Callable[[str | int], float] | None = None,
) -> Any: ...
def from_tuple(
cls: Any,
o: Any,
reuse_instances: bool | None = None,
deserialize_numbers: Callable[[str | int], float] | None = None,
) -> Any:
"""
Deserialize tuple into object.
>>> @deserialize
... class Foo:
... i: int
... s: str = 'foo'
... f: float = 100.0
... b: bool = True
>>>
>>> from_tuple(Foo, (10, 'foo', 100.0, True))
Foo(i=10, s='foo', f=100.0, b=True)
You can pass any type supported by pyserde. For example,
* `deserialize_numbers`: Optional callable to coerce numeric input to floats when the target
type is float (e.g. accept ints or numeric strings supplied by a parser).
>>> lst = [(10, 'foo', 100.0, True), (20, 'foo', 100.0, True)]
>>> from_tuple(list[Foo], lst)
[Foo(i=10, s='foo', f=100.0, b=True), Foo(i=20, s='foo', f=100.0, b=True)]
"""
return from_obj(
cls,
o,
named=False,
reuse_instances=reuse_instances,
deserialize_numbers=deserialize_numbers,
)
@dataclass
class DeField(Field[T]):
"""
Represents a field of dataclass.
"""
datavar: str | None = None
""" Name of variable which is passed in the deserialize API """
index: int = 0
""" Field index """
iterbased: bool = False
""" Iterater based deserializer or not """
def __getitem__(self, n: int) -> DeField[Any] | InnerField[Any]:
"""
Get inner `Field` from current `Field`.
`InnerField` is returned if self is of any standard collection e.g. list.
`DeField` is returned if self is Optional.
"""
typ = type_args(self.type)[n]
opts: dict[str, Any] = {
"kw_only": self.kw_only,
"case": self.case,
"alias": self.alias,
"rename": self.rename,
"skip": self.skip,
"skip_serializing": self.skip_serializing,
"skip_deserializing": self.skip_deserializing,
"skip_if": self.skip_if,
"skip_if_false": self.skip_if_false,
"skip_if_default": self.skip_if_default,
"serializer": self.serializer,
"deserializer": self.deserializer,
"flatten": self.flatten,
"parent": self.parent,
}
if (
is_list(self.type)
or is_set(self.type)
or is_dict(self.type)
or is_deque(self.type)
or is_counter(self.type)
):
return InnerField(typ, "v", datavar="v", **opts)
elif is_tuple(self.type):
return InnerField(typ, f"{self.data}[{n}]", datavar=f"{self.data}[{n}]", **opts)
else:
# For Optional etc.
# Preserve InnerField when unwrapping Optional inside a collection,
# so that data access uses the loop variable directly (e.g. "v")
# instead of indexing into it (e.g. v["v"]).
field_cls = type(self)
return field_cls(
typ,
self.name,
datavar=self.datavar,
index=self.index,
iterbased=self.iterbased,
**opts,
)
def key_field(self) -> DeField[Any]:
"""
Get inner key field for dict like class.
"""
k = self[0]
k.name = "k"
k.datavar = "k"
return k
def value_field(self) -> DeField[Any]:
"""
Get inner value field for dict like class.
"""
return self[1]
@property
def data(self) -> str:
"""
Renders the variable name that possesses the data.
e.g. tuple
* datavar property returns "data"
* data property returns "data[0]".
e.g. Optional
* datavar property returns "data"
* data property returns "data.get("field_name")".
For other types
* datavar property returns "data"
* data property returns "data["field_name"]".
"""
if self.iterbased:
return f"{self.datavar}[{self.index}]"
elif is_union(self.type) and type(None) in get_args(self.type):
return f'{self.datavar}.get("{self.conv_name()}")'
else:
return f'{self.datavar}["{self.conv_name()}"]'
@data.setter
def data(self, d: str) -> None:
self.datavar = d
def data_or(self) -> str:
if self.iterbased:
return self.data
else:
return f'{self.datavar}.get("{self.conv_name()}")'
@dataclass
class InnerField(DeField[T]):
"""
Field of Inner type. The purpose of this class is to override "data" method
for inner type codegen.
e.g.
T of list[T]
V of dict[K, V]
T of Optional[T]
"""
@property
def data(self) -> str:
return self.datavar or ""
@data.setter
def data(self, d: str) -> None:
self.datavar = d
def defields(cls: type[Any]) -> list[DeField[Any]]:
serde_scope: Scope = getattr(cls, SERDE_SCOPE)
return fields(
DeField,
cls,
skip_if_default_default=serde_scope.skip_if_default_default,
skip_if_none_default=serde_scope.skip_if_none_default,
)
@dataclass
class Renderer:
"""
Render rvalue for code generation.
"""
func: str
cls: type[Any] | None = None
legacy_class_deserializer: DeserializeFunc | None = None
import_numpy: bool = False
suppress_coerce: bool = False
""" Disable type coercing in codegen """
class_deserializer: ClassDeserializer | None = None
class_name: str | None = None
def render(self, arg: DeField[Any]) -> str:
"""
Render rvalue
"""
implemented_methods: dict[type[Any], int] = {}
class_deserializers: Iterable[ClassDeserializer] = itertools.chain(
GLOBAL_CLASS_DESERIALIZER, [self.class_deserializer] if self.class_deserializer else []
)
for n, class_deserializer in enumerate(class_deserializers):
for method in class_deserializer.__class__.deserialize.methods: # type: ignore
implemented_methods[get_args(method.signature.types[1])[0]] = n
custom_deserializer_available = arg.type in implemented_methods
if custom_deserializer_available and not arg.deserializer:
res = (
f"class_deserializers[{implemented_methods[arg.type]}].deserialize("
f"{typename(arg.type)}, {arg.data})"
)
elif arg.deserializer and arg.deserializer.inner is not default_deserializer:
res = self.custom_field_deserializer(arg)
elif is_generic(arg.type):
arg.type_args = list(get_args(arg.type))
origin = get_origin(arg.type)
assert origin
arg.type = origin
res = self.render(arg)
elif is_dataclass(arg.type):
res = self.dataclass(arg)
elif is_opt(arg.type):
res = self.opt(arg)
elif is_list(arg.type):
res = self.list(arg)
elif is_set(arg.type):
res = self.set(arg)
elif is_deque(arg.type):
res = self.deque(arg)
elif is_counter(arg.type):
res = self.counter(arg)
elif is_dict(arg.type):
res = self.dict(arg)
elif is_tuple(arg.type):
res = self.tuple(arg)
elif is_enum(arg.type):
res = self.enum(arg)
elif _is_numpy_scalar(arg.type):
from .numpy import deserialize_numpy_scalar
self.import_numpy = True
res = deserialize_numpy_scalar(arg)
elif _is_numpy_array(arg.type):
from .numpy import deserialize_numpy_array
self.import_numpy = True
res = deserialize_numpy_array(arg)
elif _is_numpy_jaxtyping(arg.type):
from .numpy import deserialize_numpy_jaxtyping_array
self.import_numpy = True
res = deserialize_numpy_jaxtyping_array(arg)
elif is_union(arg.type):
res = self.union_func(arg)
elif is_str_serializable(arg.type):
res = f"({self.c_tor_with_check(arg)}) if reuse_instances else {self.c_tor(arg)}"
elif is_datetime(arg.type):
from_iso = f"{typename(arg.type)}.fromisoformat({arg.data})"
res = f"({arg.data} if isinstance({arg.data}, {typename(arg.type)}) else {from_iso}) \
if reuse_instances else {from_iso}"
elif is_none(arg.type):
res = "None"
elif is_any(arg.type) or is_ellipsis(arg.type):
res = arg.data
elif is_pep695_type_alias(arg.type):
res = self.render(dataclasses.replace(arg, type=arg.type.__value__))
elif is_primitive(arg.type):
# For subclasses for primitives e.g. class FooStr(str), coercing is always enabled
res = self.primitive(arg, not is_primitive_subclass(arg.type))
elif isinstance(arg.type, TypeVar):
if not self.cls:
raise SerdeError("Missing cls")
index = find_generic_arg(self.cls, arg.type)
res = (
f"from_obj(get_generic_arg(maybe_generic, maybe_generic_type_vars, "
f"variable_type_args, {index}), {arg.data}, named={not arg.iterbased}, "
"reuse_instances=reuse_instances, deserialize_numbers=deserialize_numbers)"
)
elif is_literal(arg.type):
res = self.literal(arg)
else:
raise SerdeError(f"Unsupported type: {typename(arg.type)}")
if arg.supports_default():
res = self.default(arg, res)
if (
self.legacy_class_deserializer
and not arg.deserializer
and not custom_deserializer_available
):
# Rerender the code for default deserializer.
default = Renderer(
self.func, self.cls, None, suppress_coerce=self.suppress_coerce
).render(arg)
return self.custom_class_deserializer(arg, default)
else:
return res
def custom_field_deserializer(self, arg: DeField[Any]) -> str:
"""
Render rvalue for the field with custom deserializer.
"""
if not arg.deserializer:
raise SerdeError("Missing custom field deserializer")
return f"{arg.deserializer.name}({arg.data})"
def custom_class_deserializer(self, arg: DeField[Any], code: str) -> str:
"""
Render custom class deserializer.
"""
# The function takes a closure in order to execute the default value lazily.
return (
"serde_legacy_custom_class_deserializer("
f"{typename(arg.type)}, "
f"{arg.datavar}, "
f"{arg.data_or()}, "
f"default=lambda: {code})"
)
def dataclass(self, arg: DeField[Any]) -> str:
if not arg.flatten:
# e.g. "data['field']" will be used as variable name.
var = arg.data
else:
# Because the field is flattened
# e.g. "data" will be used as variable name.
assert arg.datavar
if arg.iterbased:
var = f"{arg.datavar}[{arg.index}:]"
else:
var = arg.datavar
type_args_str = [str(t).lstrip("~") for t in arg.type_args] if arg.type_args else None
opts = (
"maybe_generic=maybe_generic, maybe_generic_type_vars=maybe_generic_type_vars, "
f"variable_type_args={type_args_str}, reuse_instances=reuse_instances, "
"deserialize_numbers=deserialize_numbers"
)
if arg.is_self_referencing():
class_name = "cls"
else:
class_name = typename(arg.type)