Last active
August 6, 2020 04:18
-
-
Save rednafi/1d3873ceffbab515d4294f06302348be to your computer and use it in GitHub Desktop.
A callable that takes a dataclass object and applies appropriate target-methods based on the types of the attributes
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 dataclasses import dataclass | |
from functools import singledispatchmethod | |
from typing import List, TypeVar | |
T = TypeVar("T") | |
class Process: | |
@singledispatchmethod | |
def _process(self, arg: T) -> None: | |
raise NotImplementedError("Method has not been implemented for this type.") | |
@_process.register | |
def _(self, arg: int) -> str: | |
return f"{arg} is an integer." | |
@_process.register | |
def _(self, arg: str) -> str: | |
return f"{arg} is a string." | |
def __call__(self, data: dataclass) -> List[str]: | |
return [self._process(attr) for attr in data.__dict__.values()] | |
process = Process() | |
@dataclass | |
class Data: | |
arg_1: int | |
arg_2: str | |
data = Data(arg_1=11, arg_2="11") | |
assert process(data) == ["11 is an integer.", "11 is a string."] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment