Skip to content

Instantly share code, notes, and snippets.

@smagch
Created July 16, 2022 13:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smagch/527ee71a7bd1240088949a92e2901d7a to your computer and use it in GitHub Desktop.
Save smagch/527ee71a7bd1240088949a92e2901d7a to your computer and use it in GitHub Desktop.
Safe way for implementing singledispatch
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