|
1
|
|
|
""" |
|
2
|
|
|
PRIVATE MODULE: do not import (from) it directly. |
|
3
|
|
|
|
|
4
|
|
|
This module contains the ``StateHolder`` class and the default ``StateHolder`` |
|
5
|
|
|
instance. |
|
6
|
|
|
""" |
|
7
|
|
|
from typing import Optional |
|
8
|
|
|
import jacked |
|
9
|
|
|
|
|
10
|
|
|
|
|
11
|
|
|
class Container: |
|
12
|
|
|
""" |
|
13
|
|
|
An instance of ``Container`` holds registered injectables and can be used |
|
14
|
|
|
to inject from. |
|
15
|
|
|
""" |
|
16
|
|
|
def __init__(self): |
|
17
|
|
|
""" |
|
18
|
|
|
Constructor. |
|
19
|
|
|
""" |
|
20
|
|
|
self._injectables = list() |
|
21
|
|
|
self._subjects = set() |
|
22
|
|
|
self._instances = dict() |
|
23
|
|
|
|
|
24
|
|
|
def register(self, injectable: 'jacked.Injectable'): |
|
25
|
|
|
""" |
|
26
|
|
|
Register the given ``Injectable`` to this ``Container``. |
|
27
|
|
|
:param injectable: the ``Injectable`` that is to be registered. |
|
28
|
|
|
:return: None. |
|
29
|
|
|
""" |
|
30
|
|
|
if injectable.name not in self._subjects: |
|
31
|
|
|
self._injectables.append(injectable) |
|
32
|
|
|
self._subjects.add(injectable.subject.__name__) |
|
33
|
|
|
|
|
34
|
|
|
@property |
|
35
|
|
|
def injectables(self): |
|
36
|
|
|
""" |
|
37
|
|
|
Return all ``Injectables`` that were registered to this ``Container``. |
|
38
|
|
|
:return: a list of all ``Injectables``. |
|
39
|
|
|
""" |
|
40
|
|
|
return self._injectables |
|
41
|
|
|
|
|
42
|
|
|
def get_instance(self, hint: object) -> Optional[object]: |
|
43
|
|
|
""" |
|
44
|
|
|
Return the instance that corresponds to the given hint if there is an |
|
45
|
|
|
instance set. |
|
46
|
|
|
:param hint: a type hint that describes the object. |
|
47
|
|
|
:return: an instance for that hint or None. |
|
48
|
|
|
""" |
|
49
|
|
|
|
|
50
|
|
|
inst, _ = self._instances.get(hint, (None, None)) |
|
51
|
|
|
return inst |
|
52
|
|
|
|
|
53
|
|
|
def set_instance( |
|
54
|
|
|
self, |
|
55
|
|
|
hint: object, |
|
56
|
|
|
instance: 'jacked.Injectable', |
|
57
|
|
|
priority: int = 0): |
|
58
|
|
|
""" |
|
59
|
|
|
Set an instance for a type hint. If there already is an instance and |
|
60
|
|
|
the given priority is lesser than or equal to the priority of the |
|
61
|
|
|
existing instance, then the given instance will NOT override the |
|
62
|
|
|
existing. |
|
63
|
|
|
:param hint: a type hint that describes the object. |
|
64
|
|
|
:param instance: an instance for that hint. |
|
65
|
|
|
:param priority: the priority of the instance. |
|
66
|
|
|
:return: None. |
|
67
|
|
|
""" |
|
68
|
|
|
_, prio_existing = self._instances.get(hint, (None, -1)) |
|
69
|
|
|
if priority > prio_existing: |
|
70
|
|
|
self._instances[hint] = (instance, priority) |
|
71
|
|
|
|
|
72
|
|
|
|
|
73
|
|
|
DEFAULT_CONTAINER = Container() |
|
74
|
|
|
|