Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def __call__(self, *args, **kwargs):
"""Dispatch to first matching function."""
for sig, func in reversed(self.items()):
arguments = sig.bind(*args, **kwargs).arguments
if all(predicate(arguments[name]) for name, predicate in func.__annotations__.items()):
return func(*args, **kwargs)
raise DispatchError("No matching functions found")
def __missing__(self, types: tuple) -> Callable:
"""Find and cache the next applicable method of given types."""
self.evaluate()
if types in self:
return self[types]
groups = groupby(signature(types).__sub__, self.parents(types))
keys = groups[min(groups)] if groups else []
funcs = {self[key] for key in keys}
if len(funcs) == 1:
return self.setdefault(types, *funcs)
msg = f"{self.__name__}: {len(keys)} methods found" # type: ignore
raise DispatchError(msg, types, keys)