Completed
Push — master ( 5ea888...aa565f )
by Ramon
13s queued 11s
created

jsons._common_impl.get_class_name()   A

Complexity

Conditions 5

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 23
rs 9.1832
c 0
b 0
f 0
cc 5
nop 3
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
17
NoneType = type(None)
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
37
    @classmethod
38
    def _warn(cls, msg, *args, **kwargs):
39
        if not cls._suppress_warnings:
40
            msg_ = ('{} You can suppress warnings like this using '
41
                    'jsons.suppress_warnings().'.format(msg))
42
            warnings.warn(msg_, *args, **kwargs)
43
44
45
@cached
46
def get_class_name(cls: type,
47
                   transformer: Optional[Callable[[str], str]] = None,
48
                   fully_qualified: bool = False) -> Optional[str]:
49
    """
50
    Return the name of a class.
51
    :param cls: the class of which the name if to be returned.
52
    :param transformer: any string transformer, e.g. ``str.lower``.
53
    :param fully_qualified: if ``True`` return the fully qualified name (i.e.
54
    complete with module name).
55
    :return: the name of ``cls``, transformed if a transformer is given.
56
    """
57
    transformer = transformer or (lambda x: x)
58
    cls_name = _get_special_cases(cls)
59
    if cls_name:
60
        return transformer(cls_name)
61
    cls_name = _get_simple_name(cls)
62
    if fully_qualified:
63
        module = _get_module(cls)
64
        if module:
65
            cls_name = '{}.{}'.format(module, cls_name)
66
    cls_name = transformer(cls_name)
67
    return cls_name
68
69
70
def _get_special_cases(cls: type):
71
    if (hasattr(cls, '__qualname__')
72
            and cls.__qualname__ == 'NewType.<locals>.new_type'):
73
        return cls.__name__
74
75
76
def get_cls_from_str(cls_str: str, source: object, fork_inst) -> type:
77
    cls = getattr(builtins, cls_str, None)
78
    if cls:
79
        return cls
80
    if '[' in cls_str and ']' in cls_str:
81
        return _get_generic_cls_from_str(cls_str, source, fork_inst)
82
    try:
83
        splitted = cls_str.split('.')
84
        module_name = '.'.join(splitted[:-1])
85
        cls_name = splitted[-1]
86
        cls_module = import_module(module_name)
87
        cls = getattr(cls_module, cls_name)
88
    except (ImportError, AttributeError, ValueError):
89
        cls = _lookup_announced_class(cls_str, source, fork_inst)
90
    return cls
91
92
93
def _get_generic_cls_from_str(cls_str: str, source: object, fork_inst) -> type:
94
    # If cls_str represents a generic type, try to parse the sub types.
95
    origin_str, subtypes_str = cls_str.split('[')
96
    subtypes_str = subtypes_str[0:-1]  # Remove the ']'.
97
    origin = get_cls_from_str(origin_str, source, fork_inst)
98
    subtypes = [get_cls_from_str(s.strip(), source, fork_inst)
99
                for s in subtypes_str.split(',')]
100
    return origin[tuple(subtypes)]
101
102
103
def determine_precedence(
104
        cls: type,
105
        cls_from_meta: type,
106
        cls_from_type: type,
107
        inferred_cls: bool):
108
    order = [cls, cls_from_meta, cls_from_type]
109
    if inferred_cls:
110
        # The type from a verbose dumped object takes precedence over an
111
        # inferred type (e.g. T in List[T]).
112
        order = [cls_from_meta, cls, cls_from_type]
113
    # Now to return the first element in the order that holds a value.
114
    for elem in order:
115
        if elem:
116
            return elem
117
118
119
def get_cls_and_meta(
120
        json_obj: object,
121
        fork_inst: type) -> Tuple[Optional[type], Optional[dict]]:
122
    if isinstance(json_obj, dict) and META_ATTR in json_obj:
123
        cls_str = json_obj[META_ATTR]['classes']['/']
124
        cls = get_cls_from_str(cls_str, json_obj, fork_inst)
125
        return cls, json_obj[META_ATTR]
126
    return None, None
127
128
129
def can_match_with_none(cls: type):
130
    # Return True if cls allows None; None is a valid value with the given cls.
131
    result = cls in (Any, object, None, NoneType)
132
    if not result:
133
        cls_name = get_class_name(cls).lower()
134
        result = 'union' in cls_name and NoneType in get_union_params(cls)
135
    return result
136
137
138
def _lookup_announced_class(
139
        cls_str: str,
140
        source: object,
141
        fork_inst: type) -> type:
142
    cls = fork_inst._announced_classes.get(cls_str)
143
    if not cls:
144
        msg = ('Could not find a suitable type for "{}". Make sure it can be '
145
               'imported or that is has been announced.'.format(cls_str))
146
        raise UnknownClassError(msg, source, cls_str)
147
    return cls
148
149
150
def _get_simple_name(cls: type) -> str:
151
    if cls is None:
152
        cls = type(cls)
153
    cls_name = getattr(cls, '__name__', None)
154
    if not cls_name:
155
        cls_name = getattr(cls, '_name', None)
156
    if not cls_name:
157
        cls_name = repr(cls)
158
        cls_name = cls_name.split('[')[0]  # Remove generic types.
159
        cls_name = cls_name.split('.')[-1]  # Remove any . caused by repr.
160
        cls_name = cls_name.split(r"'>")[0]  # Remove any '>.
161
    return cls_name
162
163
164
def _get_module(cls: type) -> Optional[str]:
165
    builtin_module = str.__class__.__module__
166
    module = getattr(cls, '__module__', None)
167
    if module and module != builtin_module:
168
        return module
169