Passed
Pull Request — master (#144)
by Ramon
01:04
created

jsons.serializers.default_primitive   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 7
eloc 19
dl 0
loc 33
rs 10
c 0
b 0
f 0

2 Functions

Rating   Name   Duplication   Size   Complexity  
B default_primitive_serializer() 0 22 6
A _is_newtype() 0 3 1
1
from typing import Optional, Any
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
    # isinstance(cls, NewType) only works as of Python3.10.
32
    return hasattr(cls, '__supertype__') and 'NewType' in str(cls)
33