Imagine, that you want to bound implementation to some particular type.
Like, strings behave like this, numbers behave like that, and so on.
The good realworld example is djangorestframework.
It is build around the idea that different
data types should be converted differently to and from json format.
What is the "traditional" (or outdated if you will!) approach?
To create tons of classes for different data types and use them.
That's how we end up with classes like so:
class IntField(Field):
def from_json(self, value):
return value
def to_json(self, value):
return value
It literally has a lot of problems:
It is hard to type this code. How can I be sure that my json is parseable by the given schema?
It produces a lot of boilerplate
It has complex API: there are usually several methods to override, some fields to adjust. Moreover, we use a class, not a simple function
It is hard to extend the default library for new custom types you will have in your own project
It is hard to override
There should be a better way of solving this problem!
And typeclasses are a better way!
How would new API look like with this concept?
>>> from typing import Union
>>> from classes import typeclass
>>> @typeclass
... def to_json(instance) -> str:
... """This is a typeclass definition to convert things to json."""
>>> @to_json.instance(int)
... @to_json.instance(float)
... def _to_json_int(instance: Union[int, float]) -> str:
... return str(instance)
>>> @to_json.instance(bool)
... def _to_json_bool(instance: bool) -> str:
... return 'true' if instance else 'false'
>>> @to_json.instance(list)
... def _to_json_list(instance: list) -> str:
... return '[{0}]'.format(
... ', '.join(to_json(list_item) for list_item in instance),
... )
See how easy it is to works with types and implementation?
Typeclass is represented as a regular function, so you can use it like one: