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

TemporaryInjectionContext.rebind()   A

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nop 2
dl 0
loc 2
ccs 2
cts 2
cp 1
crap 1
rs 10
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