jsons._common_impl.get_cls_and_meta()   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 8
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 3
nop 2
1
"""
2
PRIVATE MODULE: do not import (from) it directly.
3
4
This module contains implementations of common functionality that can be used
5
throughout `jsons`.
6
"""
7
import builtins
8
import warnings
9
from importlib import import_module
10
from typing import Callable, Optional, Tuple, TypeVar, Any
11
12
from jsons._cache import cached
13
from jsons._compatibility_impl import get_union_params
14
from jsons.exceptions import UnknownClassError
15
16
NoneType = type(None)
17
JSON_KEYS = (str, int, float, bool, NoneType)
18
VALID_TYPES = (str, int, float, bool, list, tuple, set, dict, NoneType)
19
META_ATTR = '-meta'  # The name of the attribute holding meta info.
20
T = TypeVar('T')
21
22
23
class StateHolder:
24
    """
25
    This class holds the registered serializers and deserializers.
26
    """
27
    _fork_counter = 0
28
    _classes_serializers = list()
29
    _classes_deserializers = list()
30
    _serializers = dict()
31
    _deserializers = dict()
32
    _validators = dict()
33
    _classes_validators = list()
34
    _announced_classes = dict()
35
    _suppress_warnings = False
36
    _suppressed_warnings = set()
37
38
    @classmethod
39
    def _warn(cls, msg, code, *args, **kwargs):
40
        if not cls._suppress_warnings and code not in cls._suppressed_warnings:
41
            msg_ = ('{} Use suppress_warning({}) or suppress_warnings(True) to '
42
                    'turn off this message.'.format(msg, code))
43
            warnings.warn(msg_, *args, **kwargs)
44
45
46
@cached
47
def get_class_name(cls: type,
48
                   transformer: Optional[Callable[[str], str]] = None,
49
                   fully_qualified: bool = False) -> Optional[str]:
50
    """
51
    Return the name of a class.
52
    :param cls: the class of which the name if to be returned.
53
    :param transformer: any string transformer, e.g. ``str.lower``.
54
    :param fully_qualified: if ``True`` return the fully qualified name (i.e.
55
    complete with module name).
56
    :return: the name of ``cls``, transformed if a transformer is given.
57
    """
58
    transformer = transformer or (lambda x: x)
59
    cls_name = _get_special_cases(cls)
60
    if cls_name:
61
        return transformer(cls_name)
62
    cls_name = _get_simple_name(cls)
63
    if fully_qualified:
64
        module = _get_module(cls)
65
        if module:
66
            cls_name = '{}.{}'.format(module, cls_name)
67
    cls_name = transformer(cls_name)
68
    return cls_name
69
70
71
def _get_special_cases(cls: type):
72
    if (hasattr(cls, '__qualname__')
73
            and cls.__qualname__ == 'NewType.<locals>.new_type'):
74
        return cls.__name__
75
76
77
def get_cls_from_str(cls_str: str, source: object, fork_inst) -> type:
78
    cls = getattr(builtins, cls_str, None)
79
    if cls:
80
        return cls
81
    if '[' in cls_str and ']' in cls_str:
82
        return _get_generic_cls_from_str(cls_str, source, fork_inst)
83
    try:
84
        splitted = cls_str.split('.')
85
        module_name = '.'.join(splitted[:-1])
86
        cls_name = splitted[-1]
87
        cls_module = import_module(module_name)
88
        cls = getattr(cls_module, cls_name)
89
    except (ImportError, AttributeError, ValueError):
90
        cls = _lookup_announced_class(cls_str, source, fork_inst)
91
    return cls
92
93
94
def _get_generic_cls_from_str(cls_str: str, source: object, fork_inst) -> type:
95
    # If cls_str represents a generic type, try to parse the sub types.
96
    origin_str, subtypes_str = cls_str.split('[')
97
    subtypes_str = subtypes_str[0:-1]  # Remove the ']'.
98
    origin = get_cls_from_str(origin_str, source, fork_inst)
99
    subtypes = [get_cls_from_str(s.strip(), source, fork_inst)
100
                for s in subtypes_str.split(',')]
101
    return origin[tuple(subtypes)]
102
103
104
def determine_precedence(
105
        cls: type,
106
        cls_from_meta: type,
107
        cls_from_type: type,
108
        inferred_cls: bool):
109
    order = [cls, cls_from_meta, cls_from_type]
110
    if inferred_cls:
111
        # The type from a verbose dumped object takes precedence over an
112
        # inferred type (e.g. T in List[T]).
113
        order = [cls_from_meta, cls, cls_from_type]
114
    # Now to return the first element in the order that holds a value.
115
    for elem in order:
116
        if elem:
117
            return elem
118
119
120
def get_cls_and_meta(
121
        json_obj: object,
122
        fork_inst: type) -> Tuple[Optional[type], Optional[dict]]:
123
    if isinstance(json_obj, dict) and META_ATTR in json_obj:
124
        cls_str = json_obj[META_ATTR]['classes']['/']
125
        cls = get_cls_from_str(cls_str, json_obj, fork_inst)
126
        return cls, json_obj[META_ATTR]
127
    return None, None
128
129
130
def can_match_with_none(cls: type):
131
    # Return True if cls allows None; None is a valid value with the given cls.
132
    result = cls in (Any, object, None, NoneType)
133
    if not result:
134
        cls_name = get_class_name(cls).lower()
135
        result = (('union' in cls_name or 'optional' in cls_name)
136
                  and NoneType in get_union_params(cls))
137
    return result
138
139
140
def _lookup_announced_class(
141
        cls_str: str,
142
        source: object,
143
        fork_inst: type) -> type:
144
    cls = fork_inst._announced_classes.get(cls_str)
145
    if not cls:
146
        msg = ('Could not find a suitable type for "{}". Make sure it can be '
147
               'imported or that is has been announced.'.format(cls_str))
148
        raise UnknownClassError(msg, source, cls_str)
149
    return cls
150
151
152
def _get_simple_name(cls: type) -> str:
153
    if cls is None:
154
        cls = type(cls)
155
    cls_name = getattr(cls, '__name__', None)
156
    if not cls_name:
157
        cls_name = getattr(cls, '_name', None)
158
    if not cls_name:
159
        cls_name = repr(cls)
160
        cls_name = cls_name.split('[')[0]  # Remove generic types.
161
        cls_name = cls_name.split('.')[-1]  # Remove any . caused by repr.
162
        cls_name = cls_name.split(r"'>")[0]  # Remove any '>.
163
    return cls_name
164
165
166
def _get_module(cls: type) -> Optional[str]:
167
    builtin_module = str.__class__.__module__
168
    module = getattr(cls, '__module__', None)
169
    if module and module != builtin_module:
170
        return module
171