dispatcher: support arbitrary callables
authorDmitry Selyutin <ghostmansd@gmail.com>
Sun, 18 Jun 2023 18:34:46 +0000 (21:34 +0300)
committerDmitry Selyutin <ghostmansd@gmail.com>
Sun, 18 Jun 2023 18:34:46 +0000 (21:34 +0300)
src/mdis/dispatcher.py

index 6f6b9cd1be5d36bf797837039524a30ace1494ad..7c417856ca9fc389f73618673dec5756273fdb2c 100644 (file)
@@ -6,7 +6,7 @@ import types as _types
 class Hook(object):
     def __init__(self, *typeids):
         for typeid in typeids:
-            if not isinstance(typeid, type):
+            if not callable(typeid):
                 raise ValueError(typeid)
         self.__typeids = typeids
         return super().__init__()
@@ -63,7 +63,13 @@ class DispatcherMeta(type):
         return super().__new__(metacls, name, bases, ns)
 
     def dispatch(cls, typeid=object):
-        return cls.__hooks__.get(typeid)
+        hook = cls.__hooks__.get(typeid)
+        if hook is not None:
+            return hook
+        for (checker, hook) in cls.__hooks__.items():
+            if not isinstance(checker, type) and checker(typeid):
+                return hook
+        return None
 
 
 class Dispatcher(metaclass=DispatcherMeta):