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
, *args
, **kwargs
):
37 return call(dispatcher
, node
, *args
, **kwargs
)
39 return ConcreteHook(*tuple(self
))
42 class DispatcherMeta(type):
45 def __new__(metacls
, name
, bases
, ns
):
47 ishook
= lambda member
: isinstance(member
, Hook
)
49 for basecls
in reversed(bases
):
50 members
= inspect
.getmembers(basecls
, predicate
=ishook
)
51 for (_
, hook
) in members
:
52 hooks
.update(dict.fromkeys(hook
, hook
))
54 conflicts
= collections
.defaultdict(list)
55 for (key
, value
) in tuple(ns
.items()):
61 conflicts
[typeid
].append(key
)
64 for (typeid
, keys
) in conflicts
.items():
66 raise ValueError(f
"dispatch conflict: {keys!r}")
68 ns
["__hooks__"] = types
.MappingProxyType(hooks
)
70 return super().__new
__(metacls
, name
, bases
, ns
)
72 @functools.lru_cache(maxsize
=None)
73 def dispatch(cls
, typeid
=object):
74 hook
= cls
.__hooks
__.get(typeid
)
77 for (checker
, hook
) in cls
.__hooks
__.items():
78 if not isinstance(checker
, type) and checker(typeid
):
83 class Dispatcher(metaclass
=DispatcherMeta
):
84 def __call__(self
, node
, *args
, **kwargs
):
85 for typeid
in node
.__class
__.__mro
__:
86 hook
= self
.__class
__.dispatch(typeid
=typeid
)
90 hook
= self
.__class
__.dispatch()
91 return hook(self
, node
, *args
, **kwargs
)
94 def dispatch_object(self
, node
, *args
, **kwargs
):
95 raise NotImplementedError()