Completed
Push — master ( db4c81...c9ecbe )
by Ramon
25s queued 11s
created

jsons._dump_impl._check_for_recursion()   A

Complexity

Conditions 2

Size

Total Lines 6
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 2
nop 2
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
    # kwargs['_objects'].remove(id(obj))
56
    return _do_dump(obj, serializer, cls, initial, kwargs_)
57
58
59
def _do_dump(obj, serializer, cls, initial, kwargs):
60
    try:
61
        result = serializer(obj, cls=cls, **kwargs)
62
        if initial:
63
            clear()
64
        return result
65
    except Exception as err:
66
        clear()
67
        raise SerializationError(str(err)) from err
68
69
70
def dumps(obj: object,
71
          jdkwargs: Optional[Dict[str, object]] = None,
72
          *args,
73
          **kwargs) -> str:
74
    """
75
    Extend ``json.dumps``, allowing any Python instance to be dumped to a
76
    string. Any extra (keyword) arguments are passed on to ``json.dumps``.
77
78
    :param obj: the object that is to be dumped to a string.
79
    :param jdkwargs: extra keyword arguments for ``json.dumps`` (not
80
    ``jsons.dumps``!)
81
    :param args: extra arguments for ``jsons.dumps``.
82
    :param kwargs: Keyword arguments that are passed on through the
83
    serialization process.
84
    passed on to the serializer function.
85
    :return: ``obj`` as a ``str``.
86
    """
87
    jdkwargs = jdkwargs or {}
88
    dumped = dump(obj, *args, **kwargs)
89
    return json.dumps(dumped, **jdkwargs)
90
91
92
def dumpb(obj: object,
93
          encoding: str = 'utf-8',
94
          jdkwargs: Optional[Dict[str, object]] = None,
95
          *args,
96
          **kwargs) -> bytes:
97
    """
98
    Extend ``json.dumps``, allowing any Python instance to be dumped to bytes.
99
    Any extra (keyword) arguments are passed on to ``json.dumps``.
100
101
    :param obj: the object that is to be dumped to bytes.
102
    :param encoding: the encoding that is used to transform to bytes.
103
    :param jdkwargs: extra keyword arguments for ``json.dumps`` (not
104
    ``jsons.dumps``!)
105
    :param args: extra arguments for ``jsons.dumps``.
106
    :param kwargs: Keyword arguments that are passed on through the
107
    serialization process.
108
    passed on to the serializer function.
109
    :return: ``obj`` as ``bytes``.
110
    """
111
    jdkwargs = jdkwargs or {}
112
    dumped_dict = dump(obj, *args, **kwargs)
113
    dumped_str = json.dumps(dumped_dict, **jdkwargs)
114
    return dumped_str.encode(encoding=encoding)
115