Test Failed
Pull Request — master (#226)
by Steve
02:50
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 0
CRAP Score 2

Importance

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