File: hkt.rst

package info (click to toggle)
python-returns 0.26.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,652 kB
  • sloc: python: 11,000; makefile: 18
file content (327 lines) | stat: -rw-r--r-- 9,006 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
.. _hkt:

Higher Kinded Types
===================

Higher Kinded Types is a new concept for Python developers.
But, it is totally not new in general!

So, let's start with the detailed explanation: what Higher Kinded Types are?


Regular types
-------------

We can start with the very basic example.
Let's say we have a function that transforms type ``A`` into a type ``B``.
These types ``A`` and ``B`` can be some specific ones, for example:

.. code:: python

  >>> def from_a_to_b(arg: int) -> str:
  ...      return str(arg)

  >>> assert from_a_to_b(1) == '1'

That's what we already know and use. Let's scale things up!


Generics
--------

The next thing we can do with types is to write generic types.
What are generic types?
Basically, they are some types that contain other types inside.
Like ``List[int]`` is a list of integers: ``[1, 2, 3]``.
We know that ``List[int]`` has a shape of a ``list`` and contents of ``int``.

We can also write functions that work with generics:

.. code:: python

  >>> from typing import List

  >>> def all_to_str(arg: List[int]) -> List[str]:
  ...     return [str(item) for item in arg]

  >>> assert all_to_str([1, 2]) == ['1', '2']

There's one more thing about generics we want to notice at this point.
Different generics do have different numbers of type arguments:

- ``List`` has a single type argument:
  ``List[Value]`` or ``Maybe[Value]``
- ``Dict`` has two type arguments:
  ``Dict[Key, Value]`` or ``Result[Value, Error]``
- ``Generator`` has three type arguments: ``Generator[Yield, Send, Return]``
  or ``RequiresContextResult[Value, Error, Env]``

That's what we call a kind.
So, ``List`` and ``Maybe`` have a kind of ``1``,
``Dict`` and ``Result`` have kind of ``2``,
``Generator`` and ``RequiresContextResult`` have a kind of ``3``.

So, let's go one level further.


Operations on generics
----------------------

Let's say you have a function that copies all values of a passed argument.
We can define this function as:

.. code:: python

  >>> from typing import TypeVar
  >>> ValueType = TypeVar('ValueType')

  >>> def copy(arg: ValueType) -> ValueType:
  ...    ...

This function can work with any type.
It receives something and then returns the same value back.
That's the whole point of copying!

But, there are different functions, that do different things with types.
For example, we can write a function that converts
a value inside any :class:`Container1 <returns.interfaces.container.ContainerN>`
(a base class for all our containers)
from ``int`` to ``str``:

We can also write functions that work with generics:

.. code:: python

  >>> from returns.interfaces.container import Container1

  >>> def to_str(container: Container1[int]) -> Container1[str]:
  ...     return container.map(str)

And here's how it can be used:

.. code:: python

  >>> from returns.maybe import Maybe
  >>> from returns.io import IO

  >>> assert to_str(Maybe.from_value(1)) == Maybe.from_value('1')
  >>> assert to_str(IO.from_value(1)) == IO.from_value('1')

It works just fine! But! It has a very important thing inside.
All calls to ``to_str`` will return ``Container1`` type,
not something specific:

.. code:: python

  reveal_type(to_str(Maybe.from_value(1)))  # Container1[str]
  reveal_type(to_str(IO.from_value(1)))     # Container1[str]

But, we know that this is not true.
When we pass a ``Maybe`` in - we get the ``Maybe`` back.
When we pass a ``IO`` in - we get the ``IO`` back.

How can we fix this problem? With ``@overload``!

.. code:: python

  >>> from typing import overload
  >>> from returns.maybe import Maybe
  >>> from returns.io import IO

  >>> @overload
  ... def to_str(arg: Maybe[int]) -> Maybe[str]:
  ...    ...

  >>> @overload
  ... def to_str(arg: IO[int]) -> IO[str]:
  ...    ...

We kinda fixed it!
Now, our calls will reveal the correct types for these three examples:

.. code:: python

  reveal_type(to_str(Maybe.from_value(1)))  # Maybe[str]
  reveal_type(to_str(IO.from_value(1)))     # IO[str]

But, there's an important limitation with this solution:
no other types are allowed in this function anymore.
So, you will try to use it with any other type, it won't be possible.


Current limitations
-------------------

To overcome current ``@overload`` decorators limitations,
we can imagine a syntax like this:

.. code:: python

  from typing import TypeVar
  from returns.interfaces.container import Container1

  T = TypeVar('T', bound=Container1)

  def all_to_str(arg: T[int]) -> T[str]:
      ...

Sadly, this does not work. Because ``TypeVar`` cannot be used with ``[]``.
We have to find some other way.


Higher Kinded Types
-------------------

So, that's where ``returns`` saves the day!

.. note::

  Technical note: this feature requires :ref:`mypy plugin <mypy-plugins>`.

The main idea is that we can rewrite ``T[int]`` as ``Kind1[T, int]``.
Let's see how it works:

.. code:: python

  >>> from returns.primitives.hkt import Kind1
  >>> from returns.interfaces.container import ContainerN
  >>> from typing import TypeVar

  >>> T = TypeVar('T', bound=ContainerN)

  >>> def to_str(container: Kind1[T, int]) -> Kind1[T, str]:
  ...     return container.map(str)

Now, this will work almost correctly!
Why almost? Because the revealed type will be ``Kind1``.

.. code:: python

  reveal_type(to_str(Maybe.from_value(1)))  # Kind1[Maybe, str]
  reveal_type(to_str(IO.from_value(1)))     # Kind1[IO, str]

That's not something we want. We don't need ``Kind1``,
we need real ``Maybe`` or ``IO`` values.

The final solution is to decorate ``to_str`` with ``@kinded``:

.. code:: python

  >>> from returns.primitives.hkt import kinded

  >>> @kinded
  ... def to_str(container: Kind1[T, int]) -> Kind1[T, str]:
  ...     return container.map(str)

Now, it will be fully working:

.. code:: python

  reveal_type(to_str(Maybe.from_value(1)))  # Maybe[str]
  reveal_type(to_str(IO.from_value(1)))     # IO[str]

And the thing about this approach is that it will be:

1. Fully type-safe. It works with correct interface ``ContainerN``,
   returns the correct type, has correct type transformation
2. Is opened for further extension and even custom types


Kinds
-----

As it was said ``Maybe[int]``, ``Result[str, int]``,
and ``RequiresContextResult[str, int, bool]`` are different
in terms of a number of type arguments.
We support different kinds:

- ``Kind1[Maybe, int]`` is similar to ``Maybe[int]``
- ``Kind2[Result, str, int]`` is similar to ``Result[str, int]``
- ``Kind3[RequiresContextResult, str, int, bool]``
  is similar to ``RequiresContextResult[str, int, bool]``

You can use any of them freely.

Later you will learn how to
:ref:`create your own types <create-your-own-container>` that support kinds!


Further reading
---------------

- `Higher Kinded Types in Python <https://sobolevn.me/2020/10/higher-kinded-types-in-python>`_


FAQ
---

Which types you can use with KindN?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The first position in all ``KindN`` types
can be occupied by either ``Instance`` type or ``TypeVar`` with ``bound=``.

Let's see an example:

.. code:: python

  >>> from typing import TypeVar
  >>> from returns.primitives.hkt import KindN, kinded
  >>> from returns.interfaces.mappable import MappableN

  >>> _FirstType = TypeVar('_FirstType')
  >>> _SecondType = TypeVar('_SecondType')
  >>> _ThirdType = TypeVar('_ThirdType')
  >>> _MappableKind = TypeVar('_MappableKind', bound=MappableN)

  >>> @kinded
  ... def works_with_interface(
  ...     container: KindN[_MappableKind, _FirstType, _SecondType, _ThirdType],
  ... ) -> KindN[_MappableKind, str, _SecondType, _ThirdType]:
  ...     return container.map(str)

This version of ``works_with_interface`` will work
with any subtype of ``MappableN``.
Because we use ``_MappableKind`` in its definition.
And ``_MappableKind`` is a ``TypeVar`` bound to ``MappableN``.
Arguments of non ``MappableN`` subtypes will be rejected by a type-checker:

.. code:: python

  >>> from returns.maybe import Maybe
  >>> from returns.io import IO
  >>> from returns.result import Success

  >>> assert works_with_interface(Maybe.from_value(1)) == Maybe.from_value('1')
  >>> assert works_with_interface(IO.from_value(1)) == IO.from_value('1')
  >>> assert works_with_interface(Success(1)) == Success('1')

In contrast, we can work directly with some specific type,
let's say ``Maybe`` container:

.. code:: python

  >>> from returns.maybe import Maybe

  >>> @kinded
  ... def works_with_maybe(
  ...     container: KindN[Maybe, _FirstType, _SecondType, _ThirdType],
  ... ) -> KindN[Maybe, str, _SecondType, _ThirdType]:
  ...     return container.map(str)

  >>> assert works_with_maybe(Maybe.from_value(1)) == Maybe.from_value('1')

Function ``works_with_maybe`` will work correctly with ``Maybe`` instance.
Other types will be rejected.

So, choose wisely which mechanism you need.


API Reference
-------------

.. autoclasstree:: returns.primitives.hkt
   :strict:

.. automodule:: returns.primitives.hkt
  :members: