| Total Complexity | 7 |
| Total Lines | 39 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 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 |