Test Failed
Pull Request — master (#226)
by Steve
02:44
created

lagom.injection_context   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 24
dl 0
loc 39
rs 10
c 0
b 0
f 0
wmc 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A TemporaryInjectionContext.__exit__() 0 2 1
A TemporaryInjectionContext.__enter__() 0 2 1
A TemporaryInjectionContext.rebind() 0 2 1
A TemporaryInjectionContext.__init__() 0 15 4
1
from typing import Optional, Callable
2
3
from .interfaces import ReadableContainer, ExtendableContainer
4
5
6
class TemporaryInjectionContext:
7
    """
8
    Context Manager wrapper around a container which applies the supplied function on
9
    __enter__
10
    """
11
12
    _base_container: ExtendableContainer
13
    _update_function: Optional[Callable[[ReadableContainer], ReadableContainer]] = None
14
15
    def __init__(
16
        self,
17
        container: ExtendableContainer,
18
        update_function: Optional[
19
            Callable[[ReadableContainer], ReadableContainer]
20
        ] = None,
21
    ):
22
        self._base_container = container
23
        self._update_function = update_function
24
        if self._update_function:
25
            self._build_temporary_container = lambda: self._update_function(
26
                self._base_container
27
            )
28
        else:
29
            self._build_temporary_container = lambda: self._base_container.clone()
30
31
    def __enter__(self) -> ReadableContainer:
32
        return self._build_temporary_container()
33
34
    def __exit__(self, exc_type, exc_val, exc_tb):
35
        pass
36
37
    def rebind(self, new_container):
38
        return TemporaryInjectionContext(new_container, self._update_function)
39