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

_ContextBoundFunction.__init__()   A

Complexity

Conditions 1

Size

Total Lines 7
Code Lines 6

Duplication

Lines 7
Ratio 100 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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