Completed
Push — master ( e14e5b...be0326 )
by Oleksandr
01:30
created

isotopic_logging.InjectionStack.pop()   A

Complexity

Conditions 1

Size

Total Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1
Metric Value
cc 1
dl 0
loc 2
ccs 2
cts 2
cp 1
crap 1
rs 10
1
# -*- coding: utf-8 -*-
2
3 1
from collections import deque, namedtuple
4 1
from threading import local
5
6 1
from .injectors import merge_injectors
7
8
9 1
StackItem = namedtuple('StackItem', ['injector', 'parent', ])
10
11
12 1
class InjectionStack(object):
13
14 1
    def __init__(self, local):
15 1
        local.stack = deque()
16 1
        self._local = local
17
18 1
    def push(self, item):
19 1
        self._local.stack.append(item)
20
21 1
    def pop(self):
22 1
        return self._local.stack.pop()
23
24 1
    @property
25
    def top(self):
26 1
        try:
27 1
            return self._local.stack[-1]
28
        except IndexError:
29
            return None
30
31 1
    @property
32
    def is_empty(self):
33 1
        return not self._local.stack
34
35
36 1
_local = local()
37 1
_stack = InjectionStack(_local)
38
39
40 1
class InjectionContext(object):
41
42 1
    def __init__(self, injector, inherit=False):
43 1
        if _stack.is_empty:
44 1
            if callable(injector):
45 1
                injector = injector()
46
47 1
            self._push(injector)
48 1
        elif inherit:
49 1
            if callable(injector):
50 1
                injector = injector()
51
52 1
            injector = merge_injectors(_stack.top.injector, injector)
53 1
            self._push(injector)
54
55 1
    def _push(self, injector):
56 1
        item = StackItem(injector, self)
57 1
        _stack.push(item)
58
59 1
    def __enter__(self):
60 1
        return _stack.top.injector
61
62 1
    def __exit__(self, type, value, traceback):
63 1
        if _stack.top.parent is self:
64
            _stack.pop()
65