Created
July 16, 2022 13:33
-
-
Save smagch/527ee71a7bd1240088949a92e2901d7a to your computer and use it in GitHub Desktop.
Safe way for implementing singledispatch
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
from functools import singledispatch | |
from dataclasses import dataclass | |
from typing import Union, get_args | |
@dataclass | |
class Foo: | |
id: str | |
name: str | |
Command = Union[Foo, str] | |
@singledispatch | |
def dispatch(arg: Command, /): | |
raise NotImplementedError | |
@dispatch.register | |
def _(arg: Foo, /): | |
print(arg) | |
@dispatch.register | |
def _(arg: str, /): | |
print(arg) | |
assert len(get_args(Command)) + 1 == len(dispatch.registry) | |
dispatch(Foo("id", "name")) | |
dispatch("ok") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment