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
__()
22 yield from self
.__typeids
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}"
32 return f
"<{', '.join(names)}>"
34 def __call__(self
, call
):
35 class ConcreteHook(Hook
):
36 def __call__(self
, dispatcher
, node
, *args
, **kwargs
):
37 # We do not force specific arguments other than node.
38 # API users can introduce additional *args and **kwargs.
39 # However, in case they choose not to, this is fine too.
40 parameters
= tuple(inspect
.signature(call
).parameters
.values())
41 if len(parameters
) < 2:
42 raise TypeError(f
"{call.__name__}: missing required arguments")
43 if parameters
[0].kind
!= inspect
.Parameter
.POSITIONAL_OR_KEYWORD
:
44 raise TypeError(f
"{call.__name__}: incorrect self argument")
45 if parameters
[1].kind
!= inspect
.Parameter
.POSITIONAL_OR_KEYWORD
:
46 raise TypeError(f
"{call.__name__}: incorrect node argument")
48 kwargs_present
= False
49 for parameter
in parameters
:
51 inspect
.Parameter
.POSITIONAL_OR_KEYWORD
,
52 inspect
.Parameter
.VAR_POSITIONAL
,
55 inspect
.Parameter
.POSITIONAL_OR_KEYWORD
,
56 inspect
.Parameter
.VAR_KEYWORD
,
57 inspect
.Parameter
.KEYWORD_ONLY
,
59 if parameter
.kind
in positionals
:
61 elif parameter
.kind
in keywords
:
63 if args_present
and kwargs_present
:
64 return call(dispatcher
, node
, *args
, **kwargs
)
66 return call(dispatcher
, node
, *args
)
68 return call(dispatcher
, node
, **kwargs
)
70 return call(dispatcher
, node
)
72 return ConcreteHook(*tuple(self
))
75 class DispatcherMeta(type):
78 def __new__(metacls
, name
, bases
, ns
):
80 ishook
= lambda member
: isinstance(member
, Hook
)
82 for basecls
in reversed(bases
):
83 members
= inspect
.getmembers(basecls
, predicate
=ishook
)
84 for (_
, hook
) in members
:
85 hooks
.update(dict.fromkeys(hook
, hook
))
87 conflicts
= collections
.defaultdict(list)
88 for (key
, value
) in tuple(ns
.items()):
94 conflicts
[typeid
].append(key
)
97 for (typeid
, keys
) in conflicts
.items():
99 raise ValueError(f
"dispatch conflict: {keys!r}")
101 ns
["__hooks__"] = types
.MappingProxyType(hooks
)
103 return super().__new
__(metacls
, name
, bases
, ns
)
105 @functools.lru_cache(maxsize
=None)
106 def dispatch(cls
, typeid
=object):
107 hook
= cls
.__hooks
__.get(typeid
)
110 for (checker
, hook
) in cls
.__hooks
__.items():
111 if not isinstance(checker
, type) and checker(typeid
):
116 class Dispatcher(metaclass
=DispatcherMeta
):
117 def __call__(self
, node
, *args
, **kwargs
):
118 for typeid
in node
.__class
__.__mro
__:
119 hook
= self
.__class
__.dispatch(typeid
=typeid
)
123 hook
= self
.__class
__.dispatch()
124 return hook(self
, node
, *args
, **kwargs
)
127 def dispatch_object(self
, node
):
128 raise NotImplementedError()