jsons._dump_impl.dumpb()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 23
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 23
rs 9.95
c 0
b 0
f 0
cc 1
nop 5
1
"""
2
PRIVATE MODULE: do not import (from) it directly.
3
4
This module contains functionality for dumping stuff to json.
5
"""
6
import json
7
from typing import Optional, Dict
8
9
from jsons._cache import clear
10
from jsons._common_impl import StateHolder
11
from jsons._extra_impl import announce_class
12
from jsons._lizers_impl import get_serializer
13
from jsons.exceptions import SerializationError
14
15
16
def dump(obj: object,
17
         cls: Optional[type] = None,
18
         *,
19
         strict: bool = False,
20
         fork_inst: Optional[type] = StateHolder,
21
         **kwargs) -> object:
22
    """
23
    Serialize the given ``obj`` to a JSON equivalent type (e.g. dict, list,
24
    int, ...).
25
26
    The way objects are serialized can be finetuned by setting serializer
27
    functions for the specific type using ``set_serializer``.
28
29
    You can also provide ``cls`` to specify that ``obj`` needs to be serialized
30
    as if it was of type ``cls`` (meaning to only take into account attributes
31
    from ``cls``). The type ``cls`` must have a ``__slots__`` defined. Any type
32
    will do, but in most cases you may want ``cls`` to be a base class of
33
    ``obj``.
34
    :param obj: a Python instance of any sort.
35
    :param cls: if given, ``obj`` will be dumped as if it is of type ``type``.
36
    :param strict: a bool to determine if the serializer should be strict
37
    (i.e. only dumping stuff that is known to ``cls``).
38
    :param fork_inst: if given, it uses this fork of ``JsonSerializable``.
39
    :param kwargs: the keyword args are passed on to the serializer function.
40
    :return: the serialized obj as a JSON type.
41
    """
42
    cls_ = cls or obj.__class__
43
    serializer = get_serializer(cls_, fork_inst)
44
45
    # Is this the initial call or a nested?
46
    initial = kwargs.get('_initial', True)
47
48
    kwargs_ = {
49
        'fork_inst': fork_inst,
50
        '_initial': False,
51
        'strict': strict,
52
        **kwargs
53
    }
54
    announce_class(cls_, fork_inst=fork_inst)
55
    return _do_dump(obj, serializer, cls, initial, kwargs_)
56
57
58
def _do_dump(obj, serializer, cls, initial, kwargs):
59
    try:
60
        result = serializer(obj, cls=cls, **kwargs)
61
        if initial:
62
            clear()
63
        return result
64
    except Exception as err:
65
        clear()
66
        raise SerializationError(str(err)) from err
67
68
69
def dumps(obj: object,
70
          jdkwargs: Optional[Dict[str, object]] = None,
71
          *args,
72
          **kwargs) -> str:
73
    """
74
    Extend ``json.dumps``, allowing any Python instance to be dumped to a
75
    string. Any extra (keyword) arguments are passed on to ``json.dumps``.
76
77
    :param obj: the object that is to be dumped to a string.
78
    :param jdkwargs: extra keyword arguments for ``json.dumps`` (not
79
    ``jsons.dumps``!)
80
    :param args: extra arguments for ``jsons.dumps``.
81
    :param kwargs: Keyword arguments that are passed on through the
82
    serialization process.
83
    passed on to the serializer function.
84
    :return: ``obj`` as a ``str``.
85
    """
86
    jdkwargs = jdkwargs or {}
87
    dumped = dump(obj, *args, **kwargs)
88
    return json.dumps(dumped, **jdkwargs)
89
90
91
def dumpb(obj: object,
92
          encoding: str = 'utf-8',
93
          jdkwargs: Optional[Dict[str, object]] = None,
94
          *args,
95
          **kwargs) -> bytes:
96
    """
97
    Extend ``json.dumps``, allowing any Python instance to be dumped to bytes.
98
    Any extra (keyword) arguments are passed on to ``json.dumps``.
99
100
    :param obj: the object that is to be dumped to bytes.
101
    :param encoding: the encoding that is used to transform to bytes.
102
    :param jdkwargs: extra keyword arguments for ``json.dumps`` (not
103
    ``jsons.dumps``!)
104
    :param args: extra arguments for ``jsons.dumps``.
105
    :param kwargs: Keyword arguments that are passed on through the
106
    serialization process.
107
    passed on to the serializer function.
108
    :return: ``obj`` as ``bytes``.
109
    """
110
    jdkwargs = jdkwargs or {}
111
    dumped_dict = dump(obj, *args, **kwargs)
112
    dumped_str = json.dumps(dumped_dict, **jdkwargs)
113
    return dumped_str.encode(encoding=encoding)
114