Completed
Push — master ( 7be5b2...0ef053 )
by Ramon
24s queued 10s
created

jsons._dump_impl.dumps()   A

Complexity

Conditions 1

Size

Total Lines 20
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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