|
1 | | -Typeclass: the concept |
2 | | -====================== |
| 1 | +The concept |
| 2 | +=========== |
| 3 | + |
| 4 | +Typeclasses are another form of polymorphism |
| 5 | +that is widely used in some functional languages. |
| 6 | + |
| 7 | +What's the point? |
| 8 | + |
| 9 | +Well, we need to do different logic based on input type. |
| 10 | + |
| 11 | +Like ``len()`` function which |
| 12 | +works differently for ``"string"`` and ``[1, 2]``. |
| 13 | +Or ``+`` operator that works for numbers like "add" |
| 14 | +and for strings it works like "concatenate". |
| 15 | + |
| 16 | +Classes and interfaces |
| 17 | +~~~~~~~~~~~~~~~~~~~~~~ |
| 18 | + |
| 19 | +Traditionally, object oriented languages solve it via classes. |
| 20 | + |
| 21 | +And classes are hard. |
| 22 | +They have internal state, inheritance, methods (including static ones), |
| 23 | +strong type, structure, class-level constants, life-cycle, and etc. |
| 24 | + |
| 25 | +Magic methods |
| 26 | +~~~~~~~~~~~~~ |
| 27 | + |
| 28 | +That's why Python is not purely built around this idea. |
| 29 | +It also has protocols: ``__len__``, ``__iter__``, ``__add__``, etc. |
| 30 | +Which are called "magic mathods" most of the time. |
| 31 | + |
| 32 | +This really helps and keeps the language easy. |
| 33 | +But, have some serious problem: |
| 34 | +we cannot add new protocols / magic methods to the existing data types. |
| 35 | + |
| 36 | +You cannot add new methods to the ``list`` type (and that's a good thing!), |
| 37 | +you cannot also change how ``__len__`` for example work there. |
| 38 | + |
| 39 | +But, sometimes we really need this! |
| 40 | +One of the most simple example is ``json`` serialisation and deserialisation. |
| 41 | +Each type should be covered, each one works differently, they can nest. |
| 42 | +And moreover, it is 100% fine and expected |
| 43 | +to add your own types to this process. |
| 44 | + |
| 45 | +So, how does it work? |
| 46 | + |
| 47 | + |
| 48 | +Steps |
| 49 | +----- |
| 50 | + |
| 51 | +To use typeclasses you should understand these steps: |
| 52 | + |
| 53 | +.. mermaid:: |
| 54 | + :caption: Typeclass steps. |
| 55 | + |
| 56 | + graph LR |
| 57 | + F1["Typeclass definition"] --> F2["Instance definition"] |
| 58 | + F2 --> F2 |
| 59 | + F2 --> F3["Calling"] |
| 60 | + |
| 61 | +# TODO: cover each steps |
| 62 | +# TODO: json example for simple types |
| 63 | + |
| 64 | + |
| 65 | +singledispatch |
| 66 | +-------------- |
| 67 | + |
| 68 | +One may ask, what is the difference |
| 69 | +with `singledispatch <https://docs.python.org/3/library/functools.html#functools.singledispatch>`_ |
| 70 | +function from the standard library? |
0 commit comments