Typeclasses in Python ↦
In this post, I explain what typeclasses are (an alternative to subtyping polymorphism) and how to use them. I give examples in 4 very different languages to show that this concept is universal. I also show that this idea is very pythonic by comparing our classes
implementation with functools.singledispatch
.
Check how easy it is to define a typeclass with classes
:
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)
def greet_and_print(instance: Supports[Greet]) -> None:
print(greet(instance))
greet_and_print('world')
# Hello, world!
Check it out!
Discussion
Sign in or Join to comment or subscribe