Create your own container

This tutorial will guide you through the process of creating your own containers.

Step 0: Motivation

First things first, why would anyone want to create a custom containers?

The great idea about “containers” in functional programming is that it can be literally anything. There are endless use-cases.

You can create your own primitives for working with some language-or-framework specific problem, or just model your business domain.

You can copy ideas from other languages or just compose existing containers for better usability (like IOResult is the composition of IO and Result).

Example

We are going to implement a Pair container for this example. What is a Pair? Well, it is literally a pair of two values. No more, no less. Similar to a Tuple[FirstType, SecondType]. But with extra goodies.

Note

You can find all code samples here.

Step 1: Choosing right interfaces

After you came up with the idea, you will need to make a decision: what capabilities my container must have?

Basically, you should decide what Interfaces you will subtype and what methods and laws will be present in your type. You can create just a returns.interfaces.mappable.MappableN or choose a full featured returns.interfaces.container.ContainerN.

You can also choose some specific interfaces to use, like returns.interfaces.specific.result.ResultLikeN or any other.

Summing up, decide what laws and methods you need to solve your problem. And then subtype the interfaces that provide these methods and laws.

Example

What interfaces a Pair type needs?

Now, after we know about all interfaces we would need, let’s find pre-defined aliases we can reuse.

Turns out, there are some of them!

Let’s look at the result:

Note

A special note on returns.primitives.container.BaseContainer. It is a very useful class with lots of pre-defined features, like: immutability, better cloning, serialization, and comparison.

You can skip it if you wish, but it is highlighly recommended.

Later we will talk about an actual implementation of all required methods.

Step 2: Initial implementation

So, let’s start writing some code!

We would need to implement all interface methods, otherwise mypy won’t be happy. That’s what it currently says on our type definition:

error: Final class test_pair1.Pair has abstract attributes "alt", "bind", "equals", "lash", "map", "swap"

Looks like it already knows what methods should be there!

Ok, let’s drop some initial and straight forward implementation. We will later make it more complex step by step.

 1from typing import Callable, Tuple, TypeVar
 2
 3from typing_extensions import final
 4
 5from returns.interfaces import bindable, equable, lashable, swappable
 6from returns.primitives.container import BaseContainer, container_equality
 7from returns.primitives.hkt import Kind2, SupportsKind2, dekind
 8
 9_FirstType = TypeVar('_FirstType')
10_SecondType = TypeVar('_SecondType')
11
12_NewFirstType = TypeVar('_NewFirstType')
13_NewSecondType = TypeVar('_NewSecondType')
14
15
16@final
17class Pair(
18    BaseContainer,
19    SupportsKind2['Pair', _FirstType, _SecondType],
20    bindable.Bindable2[_FirstType, _SecondType],
21    swappable.Swappable2[_FirstType, _SecondType],
22    lashable.Lashable2[_FirstType, _SecondType],
23    equable.Equable,
24):
25    """
26    A type that represents a pair of something.
27
28    Like to coordinates ``(x, y)`` or two best friends.
29    Or a question and an answer.
30
31    """
32
33    def __init__(
34        self,
35        inner_value: Tuple[_FirstType, _SecondType],
36    ) -> None:
37        """Saves passed tuple as ``._inner_value`` inside this instance."""
38        super().__init__(inner_value)
39
40    # `Equable` part:
41
42    equals = container_equality  # we already have this defined for all types
43
44    # `Mappable` part via `BiMappable`:
45
46    def map(
47        self,
48        function: Callable[[_FirstType], _NewFirstType],
49    ) -> 'Pair[_NewFirstType, _SecondType]':
50        return Pair((function(self._inner_value[0]), self._inner_value[1]))
51
52    # `BindableN` part:
53
54    def bind(
55        self,
56        function: Callable[
57            [_FirstType],
58            Kind2['Pair', _NewFirstType, _SecondType],
59        ],
60    ) -> 'Pair[_NewFirstType, _SecondType]':
61        return dekind(function(self._inner_value[0]))
62
63    # `AltableN` part via `BiMappableN`:
64
65    def alt(
66        self,
67        function: Callable[[_SecondType], _NewSecondType],
68    ) -> 'Pair[_FirstType, _NewSecondType]':
69        return Pair((self._inner_value[0], function(self._inner_value[1])))
70
71    # `LashableN` part:
72
73    def lash(
74        self,
75        function: Callable[
76            [_SecondType],
77            Kind2['Pair', _FirstType, _NewSecondType],
78        ],
79    ) -> 'Pair[_FirstType, _NewSecondType]':
80        return dekind(function(self._inner_value[1]))
81
82    # `SwappableN` part:
83
84    def swap(self) -> 'Pair[_SecondType, _FirstType]':
85        return Pair((self._inner_value[1], self._inner_value[0]))

You can check our resulting source with mypy. It would be happy this time.

Step 3: New interfaces

As you can see our existing interfaces do not cover everything. We can potentially want several extra things:

  1. A method that takes two arguments and returns a new Pair instance

  2. A named constructor to create a Pair from a single value

  3. A named constructor to create a Pair from two values

We can define an interface just for this! It would be also nice to add all other interfaces there as supertypes.

That’s how it is going to look:

 1class PairLikeN(
 2    bindable.BindableN[_FirstType, _SecondType, _ThirdType],
 3    swappable.SwappableN[_FirstType, _SecondType, _ThirdType],
 4    lashable.LashableN[_FirstType, _SecondType, _ThirdType],
 5    equable.Equable,
 6):
 7    """Special interface for types that look like a ``Pair``."""
 8
 9    @abstractmethod
10    def pair(
11        self: _PairLikeKind,
12        function: Callable[
13            [_FirstType, _SecondType],
14            KindN[_PairLikeKind, _NewFirstType, _NewSecondType, _ThirdType],
15        ],
16    ) -> KindN[_PairLikeKind, _NewFirstType, _NewSecondType, _ThirdType]:
17        """Allows to work with both arguments at the same time."""
18
19    @classmethod
20    @abstractmethod
21    def from_paired(
22        cls: Type[_PairLikeKind],
23        first: _NewFirstType,
24        second: _NewSecondType,
25    ) -> KindN[_PairLikeKind, _NewFirstType, _NewSecondType, _ThirdType]:
26        """Allows to create a PairLikeN from just two values."""
27
28    @classmethod
29    @abstractmethod
30    def from_unpaired(
31        cls: Type[_PairLikeKind],
32        inner_value: _NewFirstType,
33    ) -> KindN[_PairLikeKind, _NewFirstType, _NewFirstType, _ThirdType]:
34        """Allows to create a PairLikeN from just a single object."""

Awesome! Now we have a new interface to implement. Let’s do that!

1    def pair(
2        self,
3        function: Callable[
4            [_FirstType, _SecondType],
5            Kind2['Pair', _NewFirstType, _NewSecondType],
6        ],
7    ) -> 'Pair[_NewFirstType, _NewSecondType]':
8        return dekind(function(self._inner_value[0], self._inner_value[1]))
1    @classmethod
2    def from_unpaired(
3        cls,
4        inner_value: _NewFirstType,
5    ) -> 'Pair[_NewFirstType, _NewFirstType]':
6        return Pair((inner_value, inner_value))

Looks like we are done!

Step 4: Writing tests and docs

The best part about this type is that it is pure. So, we can write our tests inside docs!

We are going to use doctests builtin module for that.

This gives us several key benefits:

  • All our docs has usage examples

  • All our examples are correct, because they are executed and tested

  • We don’t need to write regular boring tests

Let’s add docs and doctests! Let’s use map method as a short example:

 1    def map(
 2        self,
 3        function: Callable[[_FirstType], _NewFirstType],
 4    ) -> 'Pair[_NewFirstType, _SecondType]':
 5        """
 6        Changes the first type with a pure function.
 7
 8        >>> assert Pair((1, 2)).map(str) == Pair(('1', 2))
 9
10        """
11        return Pair((function(self._inner_value[0]), self._inner_value[1]))

By adding these simple tests we would already have 100% coverage. But, what if we can completely skip writing tests, but still have 100%?

Let’s discuss how we can achieve that with “Laws as values”.

Step 5: Checking laws

We already ship lots of laws with our interfaces. See our docs on laws and checking them.

Moreover, you can also define your own laws! Let’s add them to our PairLikeN interface.

Let’s start with laws definition:

 1class _LawSpec(LawSpecDef):
 2    @law_definition
 3    def pair_equality_law(
 4        raw_value: _FirstType,
 5        container: 'PairLikeN[_FirstType, _SecondType, _ThirdType]',
 6    ) -> None:
 7        """Ensures that unpaired and paired constructors work fine."""
 8        assert_equal(
 9            container.from_unpaired(raw_value),
10            container.from_paired(raw_value, raw_value),
11        )
12
13    @law_definition
14    def pair_left_identity_law(
15        pair: Tuple[_FirstType, _SecondType],
16        container: 'PairLikeN[_FirstType, _SecondType, _ThirdType]',
17        function: Callable[
18            [_FirstType, _SecondType],
19            KindN['PairLikeN', _NewFirstType, _NewSecondType, _ThirdType],
20        ],
21    ) -> None:
22        """Ensures that unpaired and paired constructors work fine."""
23        assert_equal(
24            container.from_paired(*pair).pair(function),
25            function(*pair),
26        )

And them let’s add them to our PairLikeN interface:

 1class PairLikeN(
 2    bindable.BindableN[_FirstType, _SecondType, _ThirdType],
 3    swappable.SwappableN[_FirstType, _SecondType, _ThirdType],
 4    lashable.LashableN[_FirstType, _SecondType, _ThirdType],
 5    equable.Equable,
 6):
 7    """Special interface for types that look like a ``Pair``."""
 8
 9    _laws: ClassVar[Sequence[Law]] = (
10        Law2(_LawSpec.pair_equality_law),
11        Law3(_LawSpec.pair_left_identity_law),
12    )
13
14    @abstractmethod
15    def pair(
16        self: _PairLikeKind,
17        function: Callable[
18            [_FirstType, _SecondType],
19            KindN[_PairLikeKind, _NewFirstType, _NewSecondType, _ThirdType],
20        ],
21    ) -> KindN[_PairLikeKind, _NewFirstType, _NewSecondType, _ThirdType]:
22        """Allows to work with both arguments at the same time."""
23
24    @classmethod
25    @abstractmethod
26    def from_paired(
27        cls: Type[_PairLikeKind],
28        first: _NewFirstType,
29        second: _NewSecondType,
30    ) -> KindN[_PairLikeKind, _NewFirstType, _NewSecondType, _ThirdType]:
31        """Allows to create a PairLikeN from just two values."""
32
33    @classmethod
34    @abstractmethod
35    def from_unpaired(
36        cls: Type[_PairLikeKind],
37        inner_value: _NewFirstType,
38    ) -> KindN[_PairLikeKind, _NewFirstType, _NewFirstType, _ThirdType]:
39        """Allows to create a PairLikeN from just a single object."""

The last to do is to call check_all_laws(Pair, use_init=True) to generate 10 hypothesis test cases with hundreds real test cases inside.

Here’s the final result of our brand new Pair type:

  1from abc import abstractmethod
  2from typing import Callable, ClassVar, NoReturn, Sequence, Tuple, Type, TypeVar
  3
  4from typing_extensions import final
  5
  6from returns.contrib.hypothesis.laws import check_all_laws
  7from returns.interfaces import bindable, equable, lashable, swappable
  8from returns.primitives.asserts import assert_equal
  9from returns.primitives.container import BaseContainer, container_equality
 10from returns.primitives.hkt import Kind2, KindN, SupportsKind2, dekind
 11from returns.primitives.laws import Law, Law2, Law3, LawSpecDef, law_definition
 12
 13_FirstType = TypeVar('_FirstType')
 14_SecondType = TypeVar('_SecondType')
 15_ThirdType = TypeVar('_ThirdType')
 16
 17_NewFirstType = TypeVar('_NewFirstType')
 18_NewSecondType = TypeVar('_NewSecondType')
 19
 20_PairLikeKind = TypeVar('_PairLikeKind', bound='PairLikeN')
 21
 22
 23class _LawSpec(LawSpecDef):
 24    @law_definition
 25    def pair_equality_law(
 26        raw_value: _FirstType,
 27        container: 'PairLikeN[_FirstType, _SecondType, _ThirdType]',
 28    ) -> None:
 29        """Ensures that unpaired and paired constructors work fine."""
 30        assert_equal(
 31            container.from_unpaired(raw_value),
 32            container.from_paired(raw_value, raw_value),
 33        )
 34
 35    @law_definition
 36    def pair_left_identity_law(
 37        pair: Tuple[_FirstType, _SecondType],
 38        container: 'PairLikeN[_FirstType, _SecondType, _ThirdType]',
 39        function: Callable[
 40            [_FirstType, _SecondType],
 41            KindN['PairLikeN', _NewFirstType, _NewSecondType, _ThirdType],
 42        ],
 43    ) -> None:
 44        """Ensures that unpaired and paired constructors work fine."""
 45        assert_equal(
 46            container.from_paired(*pair).pair(function),
 47            function(*pair),
 48        )
 49
 50
 51class PairLikeN(
 52    bindable.BindableN[_FirstType, _SecondType, _ThirdType],
 53    swappable.SwappableN[_FirstType, _SecondType, _ThirdType],
 54    lashable.LashableN[_FirstType, _SecondType, _ThirdType],
 55    equable.Equable,
 56):
 57    """Special interface for types that look like a ``Pair``."""
 58
 59    _laws: ClassVar[Sequence[Law]] = (
 60        Law2(_LawSpec.pair_equality_law),
 61        Law3(_LawSpec.pair_left_identity_law),
 62    )
 63
 64    @abstractmethod
 65    def pair(
 66        self: _PairLikeKind,
 67        function: Callable[
 68            [_FirstType, _SecondType],
 69            KindN[_PairLikeKind, _NewFirstType, _NewSecondType, _ThirdType],
 70        ],
 71    ) -> KindN[_PairLikeKind, _NewFirstType, _NewSecondType, _ThirdType]:
 72        """Allows to work with both arguments at the same time."""
 73
 74    @classmethod
 75    @abstractmethod
 76    def from_paired(
 77        cls: Type[_PairLikeKind],
 78        first: _NewFirstType,
 79        second: _NewSecondType,
 80    ) -> KindN[_PairLikeKind, _NewFirstType, _NewSecondType, _ThirdType]:
 81        """Allows to create a PairLikeN from just two values."""
 82
 83    @classmethod
 84    @abstractmethod
 85    def from_unpaired(
 86        cls: Type[_PairLikeKind],
 87        inner_value: _NewFirstType,
 88    ) -> KindN[_PairLikeKind, _NewFirstType, _NewFirstType, _ThirdType]:
 89        """Allows to create a PairLikeN from just a single object."""
 90
 91
 92PairLike2 = PairLikeN[_FirstType, _SecondType, NoReturn]
 93PairLike3 = PairLikeN[_FirstType, _SecondType, _ThirdType]
 94
 95
 96@final
 97class Pair(
 98    BaseContainer,
 99    SupportsKind2['Pair', _FirstType, _SecondType],
100    PairLike2[_FirstType, _SecondType],
101):
102    """
103    A type that represents a pair of something.
104
105    Like to coordinates ``(x, y)`` or two best friends.
106    Or a question and an answer.
107
108    """
109
110    def __init__(
111        self,
112        inner_value: Tuple[_FirstType, _SecondType],
113    ) -> None:
114        """Saves passed tuple as ``._inner_value`` inside this instance."""
115        super().__init__(inner_value)
116
117    # `Equable` part:
118
119    equals = container_equality  # we already have this defined for all types
120
121    # `Mappable` part via `BiMappable`:
122
123    def map(
124        self,
125        function: Callable[[_FirstType], _NewFirstType],
126    ) -> 'Pair[_NewFirstType, _SecondType]':
127        """
128        Changes the first type with a pure function.
129
130        >>> assert Pair((1, 2)).map(str) == Pair(('1', 2))
131
132        """
133        return Pair((function(self._inner_value[0]), self._inner_value[1]))
134
135    # `BindableN` part:
136
137    def bind(
138        self,
139        function: Callable[
140            [_FirstType],
141            Kind2['Pair', _NewFirstType, _SecondType],
142        ],
143    ) -> 'Pair[_NewFirstType, _SecondType]':
144        """
145        Changes the first type with a function returning another ``Pair``.
146
147        >>> def bindable(first: int) -> Pair[str, str]:
148        ...     return Pair((str(first), ''))
149
150        >>> assert Pair((1, 'b')).bind(bindable) == Pair(('1', ''))
151
152        """
153        return dekind(function(self._inner_value[0]))
154
155    # `AltableN` part via `BiMappableN`:
156
157    def alt(
158        self,
159        function: Callable[[_SecondType], _NewSecondType],
160    ) -> 'Pair[_FirstType, _NewSecondType]':
161        """
162        Changes the second type with a pure function.
163
164        >>> assert Pair((1, 2)).alt(str) == Pair((1, '2'))
165
166        """
167        return Pair((self._inner_value[0], function(self._inner_value[1])))
168
169    # `LashableN` part:
170
171    def lash(
172        self,
173        function: Callable[
174            [_SecondType],
175            Kind2['Pair', _FirstType, _NewSecondType],
176        ],
177    ) -> 'Pair[_FirstType, _NewSecondType]':
178        """
179        Changes the second type with a function returning ``Pair``.
180
181        >>> def lashable(second: int) -> Pair[str, str]:
182        ...     return Pair(('', str(second)))
183
184        >>> assert Pair(('a', 2)).lash(lashable) == Pair(('', '2'))
185
186        """
187        return dekind(function(self._inner_value[1]))
188
189    # `SwappableN` part:
190
191    def swap(self) -> 'Pair[_SecondType, _FirstType]':
192        """
193        Swaps ``Pair`` elements.
194
195        >>> assert Pair((1, 2)).swap() == Pair((2, 1))
196
197        """
198        return Pair((self._inner_value[1], self._inner_value[0]))
199
200    # `PairLikeN` part:
201
202    def pair(
203        self,
204        function: Callable[
205            [_FirstType, _SecondType],
206            Kind2['Pair', _NewFirstType, _NewSecondType],
207        ],
208    ) -> 'Pair[_NewFirstType, _NewSecondType]':
209        """
210        Creates a new ``Pair`` from an existing one via a passed function.
211
212        >>> def min_max(first: int, second: int) -> Pair[int, int]:
213        ...     return Pair((min(first, second), max(first, second)))
214
215        >>> assert Pair((2, 1)).pair(min_max) == Pair((1, 2))
216        >>> assert Pair((1, 2)).pair(min_max) == Pair((1, 2))
217
218        """
219        return dekind(function(self._inner_value[0], self._inner_value[1]))
220
221    @classmethod
222    def from_paired(
223        cls,
224        first: _NewFirstType,
225        second: _NewSecondType,
226    ) -> 'Pair[_NewFirstType, _NewSecondType]':
227        """
228        Creates a new pair from two values.
229
230        >>> assert Pair.from_paired(1, 2) == Pair((1, 2))
231
232        """
233        return Pair((first, second))
234
235    @classmethod
236    def from_unpaired(
237        cls,
238        inner_value: _NewFirstType,
239    ) -> 'Pair[_NewFirstType, _NewFirstType]':
240        """
241        Creates a new pair from a single value.
242
243        >>> assert Pair.from_unpaired(1) == Pair((1, 1))
244
245        """
246        return Pair((inner_value, inner_value))
247
248
249# Running hypothesis auto-generated tests:
250check_all_laws(Pair, use_init=True)

Step 6: Writing type-tests

Note

You can find all type-tests here.

The next thing we want is to write a type-test!

What is a type-test? This is a special type of tests for your typing. We run mypy on top of tests and use snapshots to assert the result.

We recommend to use pytest-mypy-plugins. Read more about how to use it.

Let’s start with a simple test to make sure our .pair function works correctly:

Warning

Please, don’t use env: property the way we do here. We need it since we store our example in tests/ folder. And we have to tell mypy how to find it.

 1- case: test_pair_type
 2  disable_cache: false
 3  env:
 4    # We only need this because we store this example in `tests/`
 5    # and not in our source code. Please, do not copy this line!
 6    - MYPYPATH=./tests/test_examples/test_your_container
 7
 8  # TODO: remove this config after
 9  #     mypy/typeshed/stdlib/unittest/mock.pyi:120:
10  #     error: Class cannot subclass "Any" (has type "Any")
11  # is fixed.
12  mypy_config:
13    disallow_subclassing_any = False
14  main: |
15    # Let's import our `Pair` type we defined earlier:
16    from test_pair4 import Pair
17
18    reveal_type(Pair)
19
20    def function(first: int, second: str) -> Pair[float, bool]:
21        ...
22
23    my_pair: Pair[int, str] = Pair.from_paired(1, 'a')
24    reveal_type(my_pair.pair(function))
25  out: |
26    main:4: note: Revealed type is "def [_FirstType, _SecondType] (inner_value: Tuple[_FirstType`1, _SecondType`2]) -> test_pair4.Pair[_FirstType`1, _SecondType`2]"
27    main:10: note: Revealed type is "test_pair4.Pair[builtins.float, builtins.bool]"

Ok, now, let’s try to raise an error by using it incorrectly:

 1- case: test_pair_error
 2  disable_cache: false
 3  env:
 4    # We only need this because we store this example in `tests/`
 5    # and not in our source code. Please, do not copy this line!
 6    - MYPYPATH=./tests/test_examples/test_your_container
 7
 8  # TODO: remove this config after
 9  #     mypy/typeshed/stdlib/unittest/mock.pyi:120:
10  #     error: Class cannot subclass "Any" (has type "Any")
11  # is fixed.
12  mypy_config:
13    disallow_subclassing_any = False
14  main: |
15    # Let's import our `Pair` type we defined earlier:
16    from test_pair4 import Pair
17
18    # Oups! This function has first and second types swapped!
19    def function(first: str, second: int) -> Pair[float, bool]:
20        ...
21
22    my_pair = Pair.from_paired(1, 'a')
23    my_pair.pair(function)  # this should and will error
24  out: |
25    main:9: error: Argument 1 to "pair" of "Pair" has incompatible type "Callable[[str, int], Pair[float, bool]]"; expected "Callable[[int, str], KindN[Pair[Any, Any], float, bool, Any]]"

Step 7: Reusing code

The last (but not the least!) thing you need to know is that you can reuse all code we already have for this new Pair type.

This is because of our Higher Kinded Types feature.

So, let’s say we want to use native map_() pointfree function with our new Pair type. Let’s test that it will work correctly:

 1- case: test_pair_map
 2  disable_cache: false
 3  env:
 4    # We only need this because we store this example in `tests/`
 5    # and not in our source code. Please, do not copy this line!
 6    - MYPYPATH=./tests/test_examples/test_your_container
 7
 8  # TODO: remove this config after
 9  #     mypy/typeshed/stdlib/unittest/mock.pyi:120:
10  #     error: Class cannot subclass "Any" (has type "Any")
11  # is fixed.
12  mypy_config:
13    disallow_subclassing_any = False
14  main: |
15    from test_pair4 import Pair
16    from returns.pointfree import map_
17
18    my_pair: Pair[int, int] = Pair.from_unpaired(1)
19    reveal_type(my_pair.map(str))
20    reveal_type(map_(str)(my_pair))
21  out: |
22    main:5: note: Revealed type is "test_pair4.Pair[builtins.str, builtins.int]"
23    main:6: note: Revealed type is "test_pair4.Pair[builtins.str, builtins.int]"

Yes, it works!

Now you have fully working, typed, documented, lawful, and tested primitive. You can build any other primitive you need for your business logic or infrastructure.

Context Pipelines