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

TemporaryInjectionContext.__init__()   A

Complexity

Conditions 4

Size

Total Lines 15
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4

Importance

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