dispatcher: simplify typeid traversal
[mdis.git] / src / mdis / core.py
1 class TypeidHook(object):
2 def __init__(self, *typeids):
3 for typeid in typeids:
4 if not isinstance(typeid, type):
5 raise ValueError(typeid)
6 self.__typeids = typeids
7 return super().__init__()
8
9 def __iter__(self):
10 yield from self.__typeids
11
12 def __repr__(self):
13 return f"{self.__class__.__name__}({self.__typeids!r})"
14
15 def __call__(self, call):
16 if not callable(call):
17 raise ValueError(call)
18 return CallHook(typeids=self, call=call)
19
20
21 class CallHook(object):
22 def __init__(self, typeids, call):
23 if not isinstance(typeids, TypeidHook):
24 raise ValueError(typeids)
25 if not callable(call):
26 raise ValueError(call)
27 self.__typeids = typeids
28 self.__call = call
29 return super().__init__()
30
31 def __iter__(self):
32 yield from self.__typeids
33
34 def __repr__(self):
35 return f"{self.__class__.__name__}(call={self.__call!r}, typeids={self.__typeids!r})"
36
37 def __call__(self, dispatcher, instance):
38 return self.__call(dispatcher, instance)
39
40
41 def hook(*typeids):
42 return TypeidHook(*typeids)