Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
@multimethod # type: ignore[no-redef]
def get_type(arg: Iterable):
"""Return generic type checking first value."""
return subtype(type(arg), *map(get_type, itertools.islice(arg, 1)))
def isa(*types) -> Callable:
"""Partially bound `isinstance`."""
return lambda arg: isinstance(arg, types)
class overload(collections.OrderedDict):
"""Ordered functions which dispatch based on their annotated predicates."""
__get__ = multimethod.__get__
def __new__(cls, func):
namespace = inspect.currentframe().f_back.f_locals
self = functools.update_wrapper(super().__new__(cls), func)
return namespace.get(func.__name__, self)
def __init__(self, func: Callable):
self[inspect.signature(func)] = func
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")