|
1
|
|
|
""" |
|
2
|
|
|
PRIVATE MODULE: do not import (from) it directly. |
|
3
|
|
|
|
|
4
|
|
|
This module contains the ``BaseMatcher``class. |
|
5
|
|
|
""" |
|
6
|
|
|
from typing import Any, Optional |
|
7
|
|
|
from jacked._compatibility_impl import get_naked_class |
|
8
|
|
|
from jacked._injectable import Injectable |
|
9
|
|
|
from jacked._container import Container |
|
10
|
|
|
|
|
11
|
|
|
|
|
12
|
|
|
class BaseMatcher: |
|
13
|
|
|
""" |
|
14
|
|
|
This is the base class for all matchers. A matcher tries to match some type |
|
15
|
|
|
hint with the type it can handle. For example, if a ``list`` is hinted, the |
|
16
|
|
|
``ListMatcher`` should be able to match it and will handle the injection of |
|
17
|
|
|
a ``list``. |
|
18
|
|
|
""" |
|
19
|
|
|
|
|
20
|
|
|
def can_match(self, hint: object) -> bool: |
|
21
|
|
|
""" |
|
22
|
|
|
Determine whether this matcher can match the given ``hint``. |
|
23
|
|
|
:param hint: the type hint that is to be matched. |
|
24
|
|
|
:return: ``True`` if this matcher can handle ``hint``. |
|
25
|
|
|
""" |
|
26
|
|
|
if hint is Any: |
|
27
|
|
|
return self._matching_type() is Any |
|
28
|
|
|
try: |
|
29
|
|
|
return issubclass(get_naked_class(hint), self._matching_type()) |
|
30
|
|
|
except TypeError: |
|
31
|
|
|
return False |
|
32
|
|
|
|
|
33
|
|
|
def match( |
|
34
|
|
|
self, |
|
35
|
|
|
hint: object, |
|
36
|
|
|
injectable: Injectable, |
|
37
|
|
|
container: Container) -> Optional[object]: |
|
38
|
|
|
""" |
|
39
|
|
|
See if there is a match between ``hint`` and the ``injectable``. If |
|
40
|
|
|
there is a match, return an object that corresponds to ``hint``. |
|
41
|
|
|
Otherwise, return ``None``. |
|
42
|
|
|
:param hint: the type hint that is to be matched. |
|
43
|
|
|
:param injectable: the ``Injectable`` that may be a match for ``hint``. |
|
44
|
|
|
:param container: the instance that contains all injectables. |
|
45
|
|
|
:return: an object that corresponds to ``hint`` or ``None``. |
|
46
|
|
|
""" |
|
47
|
|
|
raise NotImplementedError |
|
48
|
|
|
|
|
49
|
|
|
def priority(self) -> int: |
|
50
|
|
|
""" |
|
51
|
|
|
Determine the priority of this matcher; whether ``can_match`` of this |
|
52
|
|
|
matcher should be invoked before or after that of other matchers. A |
|
53
|
|
|
higher integer corresponds to a higher priority and thus an earlier |
|
54
|
|
|
invocation of ``can_match``. |
|
55
|
|
|
:return: the priority of this matcher as a number (0 is lowest). |
|
56
|
|
|
""" |
|
57
|
|
|
return 100 # Default. |
|
58
|
|
|
|
|
59
|
|
|
def _matching_type(self) -> type: |
|
60
|
|
|
""" |
|
61
|
|
|
Return the type this matcher can handle. |
|
62
|
|
|
:return: the type that can be handled by this matcher. |
|
63
|
|
|
""" |
|
64
|
|
|
raise NotImplementedError |
|
65
|
|
|
|