Completed
Push — master ( 87b7dd...8c4489 )
by Ramon
12s
created

jsons._common_impl.get_class_name()   B

Complexity

Conditions 6

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 11
nop 2
dl 0
loc 18
rs 8.6666
c 0
b 0
f 0
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
from typing import Callable, Optional
8
9
10
def get_class_name(cls: type,
11
                   transformer: Optional[Callable[[str], str]] = None) \
12
        -> Optional[str]:
13
    """
14
    Return the name of a class.
15
    :param cls: the class of which the name if to be returned.
16
    :param transformer: any string transformer, e.g. ``str.lower``.
17
    :return: the name of ``cls``, transformed if a transformer is given.
18
    """
19
    cls_name = getattr(cls, '__name__', getattr(cls, '_name', None))
20
    if not cls_name and hasattr(cls, '__origin__'):
21
        origin = cls.__origin__
22
        cls_name = get_class_name(origin)
23
    if not cls_name:
24
        cls_name = str(cls)
25
    if cls_name and transformer:
26
        cls_name = transformer(cls_name)
27
    return cls_name
28
29
30
def get_parents(cls: type, lizers: list) -> list:
31
    """
32
    Return a list of serializers or deserializers that can handle a parent
33
    of ``cls``.
34
    :param cls: the type that
35
    :param lizers: a list of serializers or deserializers.
36
    :return: a list of serializers or deserializers.
37
    """
38
    parents = []
39
    for cls_ in lizers:
40
        try:
41
            if issubclass(cls, cls_):
42
                parents.append(cls_)
43
        except TypeError:
44
            pass  # Some types do not support `issubclass` (e.g. Union).
45
    return parents
46