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

lagom.context_based._ContextBoundFunction.rebind()   A

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1.125

Importance

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