Total Complexity | 8 |
Total Lines | 37 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | from typing import Optional, Any, NewType |
||
2 | |||
3 | from jsons.exceptions import SerializationError |
||
4 | |||
5 | |||
6 | def default_primitive_serializer(obj: object, |
||
7 | cls: Optional[type] = None, |
||
8 | **kwargs) -> object: |
||
9 | """ |
||
10 | Serialize a primitive; simply return the given ``obj``. |
||
11 | :param obj: the primitive. |
||
12 | :param cls: the type of ``obj``. |
||
13 | :return: ``obj``. |
||
14 | """ |
||
15 | result = obj |
||
16 | |||
17 | cls_ = cls |
||
18 | if _is_newtype(cls): |
||
19 | cls_ = cls.__supertype__ |
||
20 | |||
21 | if cls_ and obj is not None and not isinstance(obj, cls_): |
||
22 | try: |
||
23 | result = cls_(obj) |
||
24 | except ValueError as err: |
||
25 | raise SerializationError('Could not cast "{}" into "{}"' |
||
26 | .format(obj, cls_.__name__)) from err |
||
27 | return result |
||
28 | |||
29 | |||
30 | def _is_newtype(cls: Any) -> bool: |
||
31 | try: |
||
32 | # isinstance(cls, NewType) only works as of Python3.10. |
||
33 | result = isinstance(cls, NewType) |
||
34 | except TypeError: |
||
35 | result = hasattr(cls, '__supertype__') |
||
36 | return result |
||
37 |