1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
|
"""
Copyright (c) 2009-2010 Christopher Michael Rossi, 2019 Arjan Molenaar & Dan Yeaw
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
from __future__ import annotations
from typing import (
Any,
Dict,
Generator,
Generic,
KeysView,
Sequence,
TypeVar,
Union,
Iterator,
)
__all__ = ("Registry", "SimpleAxis", "TypeAxis")
K = TypeVar("K")
S = TypeVar("S")
T = TypeVar("T")
V = TypeVar("V")
Axis = Union["SimpleAxis", "TypeAxis"]
class Registry(Generic[T]):
"""Registry implementation."""
def __init__(self, *axes: tuple[str, Axis]):
self._tree: _TreeNode[T] = _TreeNode()
self._axes = [axis for name, axis in axes]
self._axes_dict = {name: (i, axis) for i, (name, axis) in enumerate(axes)}
def register(self, target: T, *arg_keys: K, **kw_keys: K) -> None:
tree_node = self._tree
for key in self._align_with_axes(arg_keys, kw_keys):
tree_node = tree_node.setdefault(key, _TreeNode())
if tree_node.target is not None:
raise ValueError(
f"Registration for {target} conflicts with existing registration {tree_node.target}."
)
tree_node.target = target
def get_registration(self, *arg_keys: K, **kw_keys: K) -> T | None:
tree_node = self._tree
for key in self._align_with_axes(arg_keys, kw_keys):
if key not in tree_node:
return None
tree_node = tree_node[key]
return tree_node.target
def lookup(self, *arg_objs: V, **kw_objs: V) -> T | None:
return next(self.query(*arg_objs, **kw_objs), None)
def query(self, *arg_objs: V, **kw_objs: V) -> Iterator[T | None]:
objs = self._align_with_axes(arg_objs, kw_objs)
return filter(None, self._query(self._tree, objs, self._axes))
def _query(
self, tree_node: _TreeNode[T], objs: Sequence[V | None], axes: Sequence[Axis]
) -> Generator[T | None, None, None]:
"""Recursively traverse registration tree, from left to right, most
specific to least specific, returning the first target found on a
matching node."""
if not objs:
yield tree_node.target
else:
obj = objs[0]
# Skip non-participating nodes
if obj is None:
next_node: _TreeNode[T] | None = tree_node.get(None, None)
if next_node is not None:
yield from self._query(next_node, objs[1:], axes[1:])
else:
# Get matches on this axis and iterate from most to least specific
axis = axes[0]
for match_key in axis.matches(obj, tree_node.keys()):
yield from self._query(tree_node[match_key], objs[1:], axes[1:])
def _align_with_axes(
self, args: Sequence[S], kw: dict[str, S]
) -> Sequence[S | None]:
"""Create a list matching up all args and kwargs with their
corresponding axes, in order, using ``None`` as a placeholder for
skipped axes."""
axes_dict = self._axes_dict
aligned: list[S | None] = [None for _ in range(len(axes_dict))]
args_len = len(args)
if args_len + len(kw) > len(aligned):
raise ValueError("Cannot have more arguments than axes.")
for i, arg in enumerate(args):
aligned[i] = arg
for k, v in kw.items():
i_axis = axes_dict.get(k, None)
if i_axis is None:
raise ValueError(f"No axis with name: {k}")
i, _axis = i_axis
if aligned[i] is not None:
raise ValueError(
"Axis defined twice between positional and keyword arguments"
)
aligned[i] = v
# Trim empty tail nodes for faster look-ups
while aligned and aligned[-1] is None:
del aligned[-1]
return aligned
class _TreeNode(Generic[T], Dict[Any, Any]):
target: T | None = None
def __str__(self) -> str:
return f"<TreeNode {self.target} {dict.__str__(self)}>"
class SimpleAxis:
"""A simple axis where the key into the axis is the same as the object to
be matched (aka the identity axis). This axis behaves just like a
dictionary. You might use this axis if you are interested in registering
something by name, where you're registering an object with the string that
is the name and then using the name to look it up again later.
Subclasses can override the ``get_keys`` method for implementing
arbitrary axes.
"""
def matches(
self, obj: object, keys: KeysView[object | None]
) -> Generator[object, None, None]:
for key in [obj]:
if key in keys:
yield obj
class TypeAxis:
"""An axis which matches the class and super classes of an object in method
resolution order."""
def matches(
self, obj: object, keys: KeysView[type | None]
) -> Generator[type, None, None]:
for key in type(obj).mro():
if key in keys:
yield key
|