Nikita Sobolev

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`."""

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

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

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

# Hello, world!

Check it out!


Sign in or Join to comment or subscribe

0:00 / 0:00