Passed
Push — master ( b2eec9...5e411c )
by Max
01:09
created

_manual_partial()   A

Complexity

Conditions 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nop 1
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
"""Utilities for conditionally proxying method access to another class."""
2
3
import typing
4
5
from . import _attribute_constructor
6
7
_T = typing.TypeVar("_T")
8
9
10
class ConditionalMethod(typing.Generic[_T]):
11
    """Based on the value of the given attribute, forwards to the superclass or the source class."""
12
13
    name: str
14
    __objclass__: typing.Type[_T]
15
16
    def __init__(self, source: typing.Type[_T], field_check: str):
17
        self.source = source
18
        self.field_check = field_check
19
20
    def __set_name__(self, owner, name):
21
        self.__objclass__ = owner
22
        self.name = name
23
24
    def __get__(self, instance, owner):
25
        if getattr(owner, self.field_check):
26
            return getattr(self.source, self.name).__get__(instance, owner)
27
        target = owner if instance is None else instance
28
        return getattr(super(self.__objclass__, target), self.name)
29
30
    def __set__(self, instance, value):
31
        # Don't care about this coverage
32
        raise AttributeError  # pragma: nocover
33
34
    def __delete__(self, instance):
35
        # Don't care about this coverage
36
        raise AttributeError  # pragma: nocover
37
38
39
def _manual_partial(source: typing.Type[_T]):
40
    def wrapped(field_check: str):
41
        return ConditionalMethod(source, field_check)
42
43
    return wrapped
44
45
46
def conditional_method(
47
    source: typing.Type[_T]
48
) -> _attribute_constructor.AttributeConstructor[ConditionalMethod[_T]]:
49
    """Given a source class, return an attribute constructor that makes ConditionalMethods
50
51
    It is not recommended to reuse the return value of this function.
52
    """
53
    return _attribute_constructor.AttributeConstructor(_manual_partial(source))
54