all: construct hooks dynamically
authorDmitry Selyutin <ghostmansd@gmail.com>
Wed, 14 Jun 2023 10:19:54 +0000 (13:19 +0300)
committerDmitry Selyutin <ghostmansd@gmail.com>
Wed, 14 Jun 2023 10:19:54 +0000 (13:19 +0300)
src/mdis/core.py
src/mdis/dispatcher.py

index 7f257c86a60aabff9cc107c864933b1fd16361dd..9774cb90539c48d1e8e7745b21ecfe03970dd080 100644 (file)
@@ -1,4 +1,4 @@
-class TypeidHook(object):
+class Hook(object):
     def __init__(self, *typeids):
         for typeid in typeids:
             if not isinstance(typeid, type):
@@ -20,30 +20,12 @@ class TypeidHook(object):
         return f"<{', '.join(names)}>"
 
     def __call__(self, call):
-        if not callable(call):
-            raise ValueError(call)
-        return CallHook(typeids=self, call=call)
+        class ConcreteHook(Hook):
+            def __call__(self, dispatcher, instance):
+                return call(self=dispatcher, instance=instance)
 
-
-class CallHook(object):
-    def __init__(self, typeids, call):
-        if not isinstance(typeids, TypeidHook):
-            raise ValueError(typeids)
-        if not callable(call):
-            raise ValueError(call)
-        self.__typeids = typeids
-        self.__call = call
-        return super().__init__()
-
-    def __iter__(self):
-        yield from self.__typeids
-
-    def __repr__(self):
-        return repr(self.__typeids)
-
-    def __call__(self, dispatcher, instance):
-        return self.__call(dispatcher, instance)
+        return ConcreteHook(*tuple(self))
 
 
 def hook(*typeids):
-    return TypeidHook(*typeids)
+    return Hook(*typeids)
index 94067636b5faf11e798aa6b70869a8c96eae9ce2..f21a292006df30ea1991267b12ceb542215f3c1e 100644 (file)
@@ -6,9 +6,11 @@ from . import core as _core
 
 
 class DispatcherMeta(type):
+    __hooks__ = {}
+
     def __new__(metacls, name, bases, ns):
         hooks = {}
-        ishook = lambda member: isinstance(member, _core.CallHook)
+        ishook = lambda member: isinstance(member, _core.Hook)
 
         for basecls in reversed(bases):
             members = _inspect.getmembers(basecls, predicate=ishook)