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

lagom.experimental.context_based   A

Complexity

Total Complexity 42

Size/Duplication

Total Lines 239
Duplicated Lines 16.74 %

Test Coverage

Coverage 92.31%

Importance

Changes 0
Metric Value
eloc 167
dl 40
loc 239
ccs 108
cts 117
cp 0.9231
rs 9.0399
c 0
b 0
f 0
wmc 42

17 Methods

Rating   Name   Duplication   Size   Complexity  
A AwaitableSingleton.get() 0 6 4
A AwaitableSingleton.__init__() 0 5 1
A AsyncContextContainer.__init__() 0 10 1
B AsyncContextContainer._context_type_def() 0 16 7
A AsyncContextContainer.__aexit__() 0 4 2
A _AsyncContextBoundFunction.__getattr__() 7 7 4
A _AsyncContextBoundFunction.__init__() 7 7 1
A AsyncContextContainer.magic_partial() 0 17 2
A AsyncContextContainer.partial() 0 15 2
A AsyncContextContainer._context_resolver() 0 9 1
A AsyncContextContainer._singleton_type_def() 0 8 2
A AsyncContextContainer.clone() 0 9 1
A _AsyncContextBoundFunction.__call__() 2 2 1
C AsyncContextContainer.__aenter__() 0 23 9
A _AsyncContextBoundFunction.__async_call__() 3 3 2
A AsyncContextContainer._async_context_resolver() 0 11 1
A _AsyncContextBoundFunction.rebind() 5 5 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complexity

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like lagom.experimental.context_based often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1 1
import inspect
2 1
import logging
3 1
from asyncio import Lock
4 1
from contextlib import AsyncExitStack
5 1
from copy import copy
6 1
from functools import wraps
7 1
from typing import (
8
    Optional,
9
    Type,
10
    TypeVar,
11
    Awaitable,
12
    Generic,
13
    Collection,
14
    Union,
15
    ContextManager,
16
    AsyncContextManager,
17
    Iterator,
18
    Generator,
19
    AsyncGenerator,
20
    Callable,
21
    List,
22
)
23
24 1
from lagom.container import Container
25 1
from lagom.definitions import Alias, ConstructionWithContainer, SingletonWrapper
26 1
from lagom.exceptions import InvalidDependencyDefinition, MissingFeature
27 1
from lagom.experimental.definitions import AsyncConstructionWithContainer
28 1
from lagom.interfaces import (
29
    ReadableContainer,
30
    SpecialDepDefinition,
31
    CallTimeContainerUpdate,
32
    ContainerBoundFunction,
33
)
34
35 1
T = TypeVar("T")
36 1
X = TypeVar("X")
37
38
39 1
class AwaitableSingleton(Generic[T]):
40 1
    instance: Optional[T]
41 1
    constructor: ConstructionWithContainer[Awaitable[T]]
42 1
    container: Container
43 1
    _lock: Lock
44
45 1
    def __init__(self, constructor: ConstructionWithContainer, container: Container):
46 1
        self.instance = None
47 1
        self.constructor = constructor  # type: ignore
48 1
        self.container = container
49 1
        self._lock = Lock()
50
51 1
    async def get(self) -> T:
52 1
        if not self.instance:
53 1
            async with self._lock:
54 1
                if not self.instance:
55 1
                    self.instance = await self.constructor.get_instance(self.container)
56 1
        return self.instance
57
58
59 1 View Code Duplication
class _AsyncContextBoundFunction(ContainerBoundFunction[X]):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
60
    """
61
    Represents an instance of a function bound to an async context container
62
    """
63
64 1
    __slots__ = ("async_context_container", "partially_bound_function")
65
66 1
    async_context_container: "AsyncContextContainer"
67 1
    partially_bound_function: ContainerBoundFunction
68
69 1
    def __init__(
70
        self,
71
        async_context_container: "AsyncContextContainer",
72
        partially_bound_function: ContainerBoundFunction,
73
    ):
74 1
        self.async_context_container = async_context_container
75 1
        self.partially_bound_function = partially_bound_function
76
77 1
    def __call__(self, *args, **kwargs) -> X:
78 1
        return self.__async_call__(*args, **kwargs)
79
80 1
    async def __async_call__(self, *args, **kwargs):
81 1
        async with self.async_context_container as c:
82 1
            return await self.partially_bound_function.rebind(c)(*args, **kwargs)
83
84 1
    def rebind(self, container: ReadableContainer) -> "ContainerBoundFunction[X]":
85
        return wraps(self.partially_bound_function)(
86
            _AsyncContextBoundFunction(
87
                self.async_context_container,
88
                self.partially_bound_function.rebind(container),
89
            )
90
        )
91
92 1
    def __getattr__(self, item):
93
        if item not in self.__slots__:
94
            raise Exception(f"{item} doesn't exist")
95
        if item == "async_context_container":
96
            return self.async_context_container
97
        if item == "partially_bound_function":
98
            return self.partially_bound_function
99
100
101 1
class AsyncContextContainer(Container):
102 1
    async_exit_stack: Optional[AsyncExitStack] = None
103 1
    _context_types: Collection[Type]
104 1
    _context_singletons: Collection[Type]
105 1
    _root_context: bool = True
106
107 1
    def __init__(
108
        self,
109
        container: Container,
110
        context_types: Collection[Type],
111
        context_singletons: Collection[Type] = tuple(),
112
        log_undefined_deps: Union[bool, logging.Logger] = False,
113
    ):
114 1
        super().__init__(container, log_undefined_deps)
115 1
        self._context_types = set(context_types)
116 1
        self._context_singletons = set(context_singletons)
117
118 1
    def clone(self) -> "AsyncContextContainer":
119
        """returns a copy of the container
120
        :return:
121
        """
122 1
        return AsyncContextContainer(
123
            self,
124
            context_types=self._context_types,
125
            context_singletons=self._context_singletons,
126
            log_undefined_deps=self._undefined_logger,
127
        )
128
129 1
    async def __aenter__(self):
130 1
        if not self.async_exit_stack and self._root_context:
131 1
            self.async_exit_stack = AsyncExitStack()
132
133 1
        if self.async_exit_stack and self._root_context:
134
            # All actual context definitions happen on a clone so that there's isolation between invocations
135 1
            in_context = self.clone()
136 1
            in_context.async_exit_stack = AsyncExitStack()
137 1
            in_context._root_context = False
138
139 1
            for dep_type in self._context_types:
140 1
                managed_dep = self._context_type_def(dep_type)
141 1
                key = Awaitable[dep_type] if isinstance(managed_dep, AsyncConstructionWithContainer) else dep_type  # type: ignore
142 1
                in_context[key] = managed_dep  # type: ignore
143 1
            for dep_type in self._context_singletons:
144 1
                managed_singleton = self._singleton_type_def(dep_type)
145 1
                key = AwaitableSingleton[dep_type] if isinstance(managed_singleton, AwaitableSingleton) else dep_type  # type: ignore
146 1
                in_context[key] = managed_singleton  # type: ignore
147
148
            # The parent context manager keeps track of the inner clone
149 1
            await self.async_exit_stack.enter_async_context(in_context)
150 1
            return in_context
151 1
        return self
152
153 1
    async def __aexit__(self, exc_type, exc_val, exc_tb):
154 1
        if self.async_exit_stack:
155 1
            await self.async_exit_stack.aclose()
156 1
            self.async_exit_stack = None
157
158 1
    def partial(
159
        self,
160
        func: Callable[..., X],
161
        shared: Optional[List[Type]] = None,
162
        container_updater: Optional[CallTimeContainerUpdate] = None,
163
    ) -> ContainerBoundFunction[X]:
164 1
        if not inspect.iscoroutinefunction(func):
165
            raise MissingFeature(
166
                "AsyncContextManager currently can only deal with async functions"
167
            )
168 1
        base_partial = super(AsyncContextContainer, self).partial(
169
            func, shared, container_updater
170
        )
171
172 1
        return wraps(base_partial)(_AsyncContextBoundFunction(self, base_partial))
173
174 1
    def magic_partial(
175
        self,
176
        func: Callable[..., X],
177
        shared: Optional[List[Type]] = None,
178
        keys_to_skip: Optional[List[str]] = None,
179
        skip_pos_up_to: int = 0,
180
        container_updater: Optional[CallTimeContainerUpdate] = None,
181
    ) -> ContainerBoundFunction[X]:
182 1
        if not inspect.iscoroutinefunction(func):
183
            raise MissingFeature(
184
                "AsyncContextManager currently can only deal with async functions"
185
            )
186 1
        base_partial = super(AsyncContextContainer, self).magic_partial(
187
            func, shared, keys_to_skip, skip_pos_up_to, container_updater
188
        )
189
190 1
        return wraps(base_partial)(_AsyncContextBoundFunction(self, base_partial))
191
192 1
    def _context_type_def(self, dep_type: Type):
193 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]) or self.get_definition(AsyncGenerator[dep_type, None]) or self.get_definition(AsyncContextManager[dep_type])  # type: ignore
194 1
        if type_def is None:
195 1
            raise InvalidDependencyDefinition(
196
                f"A ContextManager[{dep_type}] should be defined. "
197
                f"This could be an Iterator[{dep_type}] or Generator[{dep_type}, None, None] "
198
                f"with the @contextmanager decorator"
199
            )
200 1
        if isinstance(type_def, Alias):
201
            # Without this we create a definition that points to
202
            # itself.
203 1
            type_def = copy(type_def)
204 1
            type_def.skip_definitions = True
205 1
        if self.get_definition(AsyncGenerator[dep_type, None]) or self.get_definition(AsyncContextManager[dep_type]):  # type: ignore
206 1
            return AsyncConstructionWithContainer(lambda c: self._async_context_resolver(c, type_def))  # type: ignore
207 1
        return ConstructionWithContainer(lambda c: self._context_resolver(c, type_def))  # type: ignore
208
209 1
    def _context_resolver(self, c: ReadableContainer, type_def: SpecialDepDefinition):
210
        """
211
        Takes an existing definition which must be a context manager. Returns
212
        the value of the context manager from __enter__ and then places the
213
        __exit__ in this container's exit stack
214
        """
215 1
        assert self.async_exit_stack, "Types can only be resolved within an async with"
216 1
        context_manager = type_def.get_instance(c)
217 1
        return self.async_exit_stack.enter_context(context_manager)
218
219 1
    def _async_context_resolver(
220
        self, c: ReadableContainer, type_def: SpecialDepDefinition
221
    ):
222
        """
223
        Takes an existing definition which must be a context manager. Returns
224
        the value of the context manager from __aenter__ and then places the
225
        __aexit__ in this container's exit stack
226
        """
227 1
        assert self.async_exit_stack, "Types can only be resolved within an async with"
228 1
        context_manager = type_def.get_instance(c)
229 1
        return self.async_exit_stack.enter_async_context(context_manager)
230
231 1
    def _singleton_type_def(self, dep_type: Type):
232
        """
233
        The same as context_type_def but acts as a singleton within this container
234
        """
235 1
        type_def = self._context_type_def(dep_type)
236 1
        if isinstance(type_def, AsyncConstructionWithContainer):
237 1
            return AwaitableSingleton(type_def, self)
238
        return SingletonWrapper(type_def)
239