Created
August 18, 2022 08:50
-
-
Save L3viathan/854c41f0ce835bbdca43e1f641179afa to your computer and use it in GitHub Desktop.
Multiple dispatch via type annotations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def overload(fn, overloads={}, nope=object()): | |
def wrapper(*args, **kwargs): | |
for sig, func in overloads.get(fn.__qualname__, []): | |
try: | |
bound = sig.bind(*args, **kwargs) | |
except TypeError: | |
continue | |
for name, value in bound.arguments.items(): | |
if not isinstance(value, func.__annotations__[name]): | |
break | |
else: | |
return func(*args, **kwargs) | |
raise TypeError("beep boop") | |
overloads.setdefault(fn.__qualname__, []).append((inspect.signature(fn), fn)) | |
return wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment