Last Updated: June 30, 2021
·
24
· sobolevn

Define a typeclass in Python

Repository: https://github.com/dry-python/classes/

from dataclasses import dataclass
from classes import AssociatedType, Supports, typeclass

class Greet(AssociatedType):
    """Special type to represent that some instance can `greet`."""

@typeclass(Greet)
def greet(instance) -> str:
    """No implementation needed."""

@greet.instance(str)
def _greet_str(instance: str) -> str:
    return 'Hello, {0}!'.format(instance)

@greet.instance(MyUser)
def _greet_myuser(instance: MyUser) -> str:
     return 'Hello again, {0}'.format(instance.name)

def greet_and_print(instance: Supports[Greet]) -> None:
    print(greet(instance))

greet_and_print('world')
# Hello, world!

greet_and_print(MyUser(name='example'))
# Hello again, example

greet_and_print(1)  # both runtime and mypy errors