dispatcher: support args and kwargs
[mdis.git] / src / mdis / dispatcher.py
1 __all__ = [
2 "Dispatcher",
3 "DispatcherMeta",
4 "Hook",
5 ]
6
7 import collections
8 import functools
9 import inspect
10 import types
11
12
13 class Hook(object):
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__()
20
21 def __iter__(self):
22 yield from self.__typeids
23
24 def __repr__(self):
25 names = []
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}"
31 names.append(name)
32 return f"<{', '.join(names)}>"
33
34 def __call__(self, call):
35 class ConcreteHook(Hook):
36 def __call__(self, dispatcher, instance, *args, **kwargs):
37 return call(self=dispatcher, instance=instance,
38 *args, **kwargs)
39
40 return ConcreteHook(*tuple(self))
41
42
43 class DispatcherMeta(type):
44 __hooks__ = {}
45
46 def __new__(metacls, name, bases, ns):
47 hooks = {}
48 ishook = lambda member: isinstance(member, Hook)
49
50 for basecls in reversed(bases):
51 members = inspect.getmembers(basecls, predicate=ishook)
52 for (_, hook) in members:
53 hooks.update(dict.fromkeys(hook, hook))
54
55 conflicts = collections.defaultdict(list)
56 for (key, value) in tuple(ns.items()):
57 if not ishook(value):
58 continue
59 hook = value
60 for typeid in hook:
61 hooks[typeid] = hook
62 conflicts[typeid].append(key)
63 ns[key] = hook
64
65 for (typeid, keys) in conflicts.items():
66 if len(keys) > 1:
67 raise ValueError(f"dispatch conflict: {keys!r}")
68
69 ns["__hooks__"] = types.MappingProxyType(hooks)
70
71 return super().__new__(metacls, name, bases, ns)
72
73 @functools.lru_cache(maxsize=None)
74 def dispatch(cls, typeid=object):
75 hook = cls.__hooks__.get(typeid)
76 if hook is not None:
77 return hook
78 for (checker, hook) in cls.__hooks__.items():
79 if not isinstance(checker, type) and checker(typeid):
80 return hook
81 return None
82
83
84 class Dispatcher(metaclass=DispatcherMeta):
85 def __call__(self, instance, *args, **kwargs):
86 for typeid in instance.__class__.__mro__:
87 hook = self.__class__.dispatch(typeid=typeid)
88 if hook is not None:
89 break
90 if hook is None:
91 hook = self.__class__.dispatch()
92 return hook(dispatcher=self, instance=instance, *args, **kwargs)
93
94 @Hook(object)
95 def dispatch_object(self, instance, *args, **kwargs):
96 raise NotImplementedError()