|
1
|
|
|
""" |
|
2
|
|
|
PRIVATE MODULE: do not import (from) it directly. |
|
3
|
|
|
|
|
4
|
|
|
This module contains functionality for loading stuff from json. |
|
5
|
|
|
""" |
|
6
|
|
|
from typing import Type, List, Any, Dict, Callable |
|
7
|
|
|
|
|
8
|
|
|
from jsons._common_impl import T |
|
9
|
|
|
from jsons._dump_impl import dump |
|
10
|
|
|
from jsons._load_impl import load |
|
11
|
|
|
|
|
12
|
|
|
|
|
13
|
|
|
def transform( |
|
14
|
|
|
obj: object, |
|
15
|
|
|
cls: Type[T], |
|
16
|
|
|
*, |
|
17
|
|
|
mapper: Callable[[Dict[str, Any]], Dict[str, Any]] = None, |
|
18
|
|
|
dump_cls: type = None, |
|
19
|
|
|
dump_args: List[Any] = None, |
|
20
|
|
|
dump_kwargs: List[Dict[str, Any]] = None, |
|
21
|
|
|
**kwargs) -> T: |
|
22
|
|
|
""" |
|
23
|
|
|
Transform the given ``obj`` to an instance of ``cls``. |
|
24
|
|
|
|
|
25
|
|
|
:param obj: the object that is to be transformed into a type of ``cls``. |
|
26
|
|
|
:param cls: the type that ``obj`` is to be transformed into. |
|
27
|
|
|
:param mapper: a callable that takes the dumped dict and returns a mapped |
|
28
|
|
|
dict right before it is loaded into ``cls``. |
|
29
|
|
|
:param dump_cls: the ``cls`` parameter that is given to ``dump``. |
|
30
|
|
|
:param dump_args: the ``args`` parameter that is given to ``dump``. |
|
31
|
|
|
:param dump_kwargs: the ``kwargs`` parameter that is given to ``dump``. |
|
32
|
|
|
:param kwargs: any keyword arguments that are given to ``load``. |
|
33
|
|
|
:return: an instance of ``cls``. |
|
34
|
|
|
""" |
|
35
|
|
|
dump_args_ = dump_args or [] |
|
36
|
|
|
dump_kwargs_ = dump_kwargs or {} |
|
37
|
|
|
dumped = dump(obj, dump_cls, *dump_args_, **dump_kwargs_) |
|
38
|
|
|
mapper_ = mapper or (lambda x: x) |
|
39
|
|
|
dumped_mapped = mapper_(dumped) |
|
40
|
|
|
return load(dumped_mapped, cls, **kwargs) |
|
41
|
|
|
|