Passed
Pull Request — master (#42)
by Ramon
52s
created

jsons._compatibility_impl.tuple_with_ellipsis()   A

Complexity

Conditions 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 2
nop 1
1
"""
2
PRIVATE MODULE: do not import (from) it directly.
3
4
This module contains functionality for supporting the compatibility of jsons
5
with multiple Python versions.
6
"""
7
import sys
8
import typing
9
from enum import Enum
10
11
12
class Flag(Enum):
13
    """
14
    This is a light version of the Flag enum type that was introduced in
15
    Python3.6. It supports the use of pipes for members (Flag.A | Flag.B).
16
    """
17
18
    @classmethod
19
    def _get_inst(cls, value):
20
        try:
21
            result = cls(value)
22
        except ValueError:
23
            pseudo_member = object.__new__(cls)
24
            pseudo_member._value_ = value
25
            contained = [elem.name for elem in cls if elem in pseudo_member]
26
            pseudo_member._name_ = '|'.join(contained)
27
            result = pseudo_member
28
        return result
29
30
    def __or__(self, other: 'Flag') -> 'Flag':
31
        new_value = other.value | self.value
32
        return self._get_inst(new_value)
33
34
    def __contains__(self, item: 'Flag') -> bool:
35
        return item.value == self.value & item.value
36
37
    __ror__ = __or__
38
39
40
def tuple_with_ellipsis(tup: type) -> bool:
41
    # Python3.5: Tuples have __tuple_use_ellipsis__
42
    # Python3.7: Tuples have __args__
43
    use_el = getattr(tup, '__tuple_use_ellipsis__', None)
44
    if use_el is None:
45
        use_el = tup.__args__[-1] is ...
46
    return use_el
47
48
49
def get_union_params(un: type) -> list:
50
    # Python3.5: Unions have __union_params__
51
    # Python3.7: Unions have __args__
52
    return getattr(un, '__union_params__', getattr(un, '__args__', None))
53
54
55
def get_naked_class(cls: type) -> type:
56
    # Python3.5: typing classes have __extra__
57
    # Python3.6: typing classes have __extra__
58
    # Python3.7: typing classes have __origin__
59
    # Return the non-generic class (e.g. dict) of a generic type (e.g. Dict).
60
    attr = '__origin__'
61
    if sys.version_info[1] in (5, 6):
62
        attr = '__extra__'
63
    return getattr(cls, attr, cls)
64
65
66
def get_type_hints(func: callable):
67
    # Python3.5: get_type_hints raises on classes without explicit constructor
68
    try:
69
        result = typing.get_type_hints(func)
70
    except AttributeError:
71
        result = {}
72
    return result
73