Passed
Pull Request — master (#226)
by Steve
02:59
created

lagom.context_based._ContextBoundFunction.rebind()   A

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 4

Duplication

Lines 4
Ratio 100 %

Code Coverage

Tests 1
CRAP Score 1.125

Importance

Changes 0
Metric Value
cc 1
eloc 4
nop 2
dl 4
loc 4
ccs 1
cts 2
cp 0.5
crap 1.125
rs 10
c 0
b 0
f 0
1 1
import logging
2 1
from contextlib import ExitStack
3 1
from copy import copy
4 1
from typing import (
5
    Collection,
6
    Union,
7
    Type,
8
    TypeVar,
9
    Optional,
10
    cast,
11
    ContextManager,
12
    Iterator,
13
    Generator,
14
    Callable,
15
    List,
16
    Dict,
17
)
18
19 1
from lagom.container import Container
20 1
from lagom.functools import wraps
21 1
from lagom.compilaton import mypyc_attr
22 1
from lagom.definitions import ConstructionWithContainer, SingletonWrapper, Alias
23 1
from lagom.exceptions import InvalidDependencyDefinition
24 1
from lagom.interfaces import (
25
    ReadableContainer,
26
    SpecialDepDefinition,
27
    CallTimeContainerUpdate,
28
    ContainerBoundFunction,
29
)
30
31 1
X = TypeVar("X")
32
33
34 1 View Code Duplication
class _ContextBoundFunction(ContainerBoundFunction[X]):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
35
    """
36
    Represents an instance of a function bound to a context container
37
    """
38
39 1
    __slots__ = ("context_container", "partially_bound_function")
40
41 1
    context_container: "ContextContainer"
42 1
    partially_bound_function: ContainerBoundFunction
43 1
    __dict__: Dict
44
45 1
    def __init__(
46
        self,
47
        context_container: "ContextContainer",
48
        partially_bound_function: ContainerBoundFunction,
49
    ):
50 1
        self.context_container = context_container
51 1
        self.partially_bound_function = partially_bound_function
52
53 1
    def __call__(self, *args, **kwargs) -> X:
54 1
        with self.context_container as c:
55 1
            return self.partially_bound_function.rebind(c)(*args, **kwargs)
56
57 1
    def rebind(self, container: ReadableContainer) -> "ContainerBoundFunction[X]":
58
        return wraps(self.partially_bound_function)(
59
            _ContextBoundFunction(
60
                self.context_container, self.partially_bound_function.rebind(container)
61
            )
62
        )
63
64 1
    def __getattribute__(self, item):
65 1
        if item == "__dict__":
66
            return {}
67 1
        return super().__getattribute__(item)
68
69
70 1
@mypyc_attr(allow_interpreted_subclasses=True)
71 1
class ContextContainer(Container):
72
    """
73
    Wraps a regular container but is a ContextManager for use within a `with`.
74
75
    >>> from tests.examples import SomeClass, SomeClassManager
76
    >>> from lagom import Container
77
    >>> from typing import ContextManager
78
    >>>
79
    >>> # The regular container
80
    >>> c = Container()
81
    >>>
82
    >>> # register a context manager for SomeClass
83
    >>> c[ContextManager[SomeClass]] = SomeClassManager
84
    >>>
85
    >>> context_c = ContextContainer(c, context_types=[SomeClass])
86
    >>> with context_c as c:
87
    ...     c[SomeClass]
88
    <tests.examples.SomeClass object at ...>
89
    """
90
91 1
    exit_stack: Optional[ExitStack] = None
92 1
    _context_types: Collection[Type]
93 1
    _context_singletons: Collection[Type]
94
95 1
    def __init__(
96
        self,
97
        container: Container,
98
        context_types: Collection[Type],
99
        context_singletons: Collection[Type] = tuple(),
100
        log_undefined_deps: Union[bool, logging.Logger] = False,
101
    ):
102 1
        self._context_types = context_types
103 1
        self._context_singletons = context_singletons
104 1
        super().__init__(container, log_undefined_deps)
105
106 1
    def clone(self) -> "ContextContainer":
107
        """returns a copy of the container
108
        :return:
109
        """
110 1
        return ContextContainer(
111
            self,
112
            context_types=self._context_types,
113
            context_singletons=self._context_singletons,
114
            log_undefined_deps=self._undefined_logger,
115
        )
116
117 1
    def __enter__(self):
118 1
        if not self.exit_stack:
119
            # All actual context definitions happen on a clone so that there's isolation between invocations
120 1
            in_context = self.clone()
121 1
            for dep_type in set(self._context_types):
122 1
                in_context[dep_type] = self._context_type_def(dep_type)
123 1
            for dep_type in set(self._context_singletons):
124 1
                in_context[dep_type] = self._singleton_type_def(dep_type)
125 1
            in_context.exit_stack = ExitStack()
126
127
            # The parent context manager keeps track of the inner clone
128 1
            self.exit_stack = ExitStack()
129 1
            self.exit_stack.enter_context(in_context)
130 1
            return in_context
131 1
        return self
132
133 1
    def __exit__(self, exc_type, exc_val, exc_tb):
134 1
        if self.exit_stack:
135 1
            self.exit_stack.close()
136 1
            self.exit_stack = None
137
138 1
    def partial(
139
        self,
140
        func: Callable[..., X],
141
        shared: Optional[List[Type]] = None,
142
        container_updater: Optional[CallTimeContainerUpdate] = None,
143
    ) -> ContainerBoundFunction[X]:
144 1
        base_partial = super(ContextContainer, self).partial(
145
            func, shared, container_updater
146
        )
147
148 1
        return wraps(base_partial)(_ContextBoundFunction(self, base_partial))
149
150 1
    def magic_partial(
151
        self,
152
        func: Callable[..., X],
153
        shared: Optional[List[Type]] = None,
154
        keys_to_skip: Optional[List[str]] = None,
155
        skip_pos_up_to: int = 0,
156
        container_updater: Optional[CallTimeContainerUpdate] = None,
157
    ) -> ContainerBoundFunction[X]:
158 1
        base_partial = super(ContextContainer, self).magic_partial(
159
            func, shared, keys_to_skip, skip_pos_up_to, container_updater
160
        )
161
162 1
        return wraps(base_partial)(_ContextBoundFunction(self, base_partial))
163
164 1
    def _context_type_def(self, dep_type: Type):
165 1
        type_def = self.get_definition(ContextManager[dep_type]) or self.get_definition(Iterator[dep_type]) or self.get_definition(Generator[dep_type, None, None])  # type: ignore
166 1
        if type_def is None:
167 1
            raise InvalidDependencyDefinition(
168
                f"A ContextManager[{dep_type}] should be defined. "
169
                f"This could be an Iterator[{dep_type}] or Generator[{dep_type}, None, None] "
170
                f"with the @contextmanager decorator"
171
            )
172 1
        if isinstance(type_def, Alias):
173
            # Without this we create a definition that points to
174
            # itself.
175 1
            type_def = copy(type_def)
176 1
            type_def.skip_definitions = True
177 1
        return ConstructionWithContainer(lambda c: self._context_resolver(c, type_def))  # type: ignore
178
179 1
    def _singleton_type_def(self, dep_type: Type):
180
        """
181
        The same as context_type_def but acts as a singleton within this container
182
        """
183 1
        return SingletonWrapper(self._context_type_def(dep_type))
184
185 1
    def _context_resolver(self, c: ReadableContainer, type_def: SpecialDepDefinition):
186
        """
187
        Takes an existing definition which must be a context manager. Returns
188
        the value of the context manager from __enter__ and then places the
189
        __exit__ in this container's exit stack
190
        """
191 1
        assert self.exit_stack, "Types can only be resolved within a with"
192 1
        context_manager = cast(ContextManager, type_def.get_instance(c))
193
        return self.exit_stack.enter_context(context_manager)
194