63b1ebb0888b53be59d4b16829fdc9e5715e48c7
14 def __init__(self
, *typeids
):
15 for typeid
in typeids
:
16 if not callable(typeid
):
17 raise ValueError(typeid
)
18 self
.__typeids
= typeids
19 return super().__init
__()
22 yield from self
.__typeids
26 for typeid
in self
.__typeids
:
27 name
= typeid
.__qualname
__
28 module
= typeid
.__module
__
29 if module
not in ("builtins",):
30 name
= f
"{module}.{name}"
32 return f
"<{', '.join(names)}>"
34 def __call__(self
, call
):
35 class ConcreteHook(Hook
):
36 def __call__(self
, dispatcher
, node
, *arguments
):
38 return call(dispatcher
, node
, *arguments
)
40 return call(dispatcher
, node
)
42 return ConcreteHook(*tuple(self
))
45 class DispatcherMeta(type):
48 def __new__(metacls
, name
, bases
, ns
):
50 ishook
= lambda member
: isinstance(member
, Hook
)
52 for basecls
in reversed(bases
):
53 members
= inspect
.getmembers(basecls
, predicate
=ishook
)
54 for (_
, hook
) in members
:
55 hooks
.update(dict.fromkeys(hook
, hook
))
57 conflicts
= collections
.defaultdict(list)
58 for (key
, value
) in tuple(ns
.items()):
64 conflicts
[typeid
].append(key
)
67 for (typeid
, keys
) in conflicts
.items():
69 raise ValueError(f
"dispatch conflict: {keys!r}")
71 ns
["__hooks__"] = types
.MappingProxyType(hooks
)
73 return super().__new
__(metacls
, name
, bases
, ns
)
75 @functools.lru_cache(maxsize
=None)
76 def dispatch(cls
, typeid
=object):
77 hook
= cls
.__hooks
__.get(typeid
)
80 for (checker
, hook
) in cls
.__hooks
__.items():
81 if not isinstance(checker
, type) and checker(typeid
):
86 class Dispatcher(metaclass
=DispatcherMeta
):
87 def __call__(self
, node
, *arguments
):
88 for typeid
in node
.__class
__.__mro
__:
89 hook
= self
.__class
__.dispatch(typeid
=typeid
)
93 hook
= self
.__class
__.dispatch()
94 return hook(self
, node
, *arguments
)
97 def dispatch_object(self
, node
, *arguments
):
98 raise NotImplementedError()