From: Dmitry Selyutin Date: Wed, 14 Jun 2023 10:19:54 +0000 (+0300) Subject: all: construct hooks dynamically X-Git-Url: https://git.libre-soc.org/?a=commitdiff_plain;h=f4e301938215ea9c45b869d61b25034c3b7d1a7e;p=mdis.git all: construct hooks dynamically --- diff --git a/src/mdis/core.py b/src/mdis/core.py index 7f257c8..9774cb9 100644 --- a/src/mdis/core.py +++ b/src/mdis/core.py @@ -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) diff --git a/src/mdis/dispatcher.py b/src/mdis/dispatcher.py index 9406763..f21a292 100644 --- a/src/mdis/dispatcher.py +++ b/src/mdis/dispatcher.py @@ -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)