File: failable.py

package info (click to toggle)
python-returns 0.26.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,652 kB
  • sloc: python: 11,000; makefile: 18
file content (266 lines) | stat: -rw-r--r-- 7,967 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
from abc import abstractmethod
from collections.abc import Callable, Sequence
from typing import ClassVar, TypeVar, final

from typing_extensions import Never

from returns.interfaces import container as _container
from returns.interfaces import lashable, swappable
from returns.primitives.asserts import assert_equal
from returns.primitives.hkt import KindN
from returns.primitives.laws import (
    Law,
    Law2,
    Law3,
    Lawful,
    LawSpecDef,
    law_definition,
)

_FirstType = TypeVar('_FirstType')
_SecondType = TypeVar('_SecondType')
_ThirdType = TypeVar('_ThirdType')
_UpdatedType = TypeVar('_UpdatedType')

_SingleFailableType = TypeVar('_SingleFailableType', bound='SingleFailableN')
_DiverseFailableType = TypeVar('_DiverseFailableType', bound='DiverseFailableN')

# Used in laws:
_NewFirstType = TypeVar('_NewFirstType')


@final
class _FailableLawSpec(LawSpecDef):
    """
    Failable laws.

    We need to be sure that ``.lash`` won't lash success types.
    """

    __slots__ = ()

    @law_definition
    def lash_short_circuit_law(
        raw_value: _FirstType,
        container: 'FailableN[_FirstType, _SecondType, _ThirdType]',
        function: Callable[
            [_SecondType],
            KindN['FailableN', _FirstType, _NewFirstType, _ThirdType],
        ],
    ) -> None:
        """Ensures that you cannot lash a success."""
        assert_equal(
            container.from_value(raw_value),
            container.from_value(raw_value).lash(function),
        )


class FailableN(
    _container.ContainerN[_FirstType, _SecondType, _ThirdType],
    lashable.LashableN[_FirstType, _SecondType, _ThirdType],
    Lawful['FailableN[_FirstType, _SecondType, _ThirdType]'],
):
    """
    Base type for types that can fail.

    It is a raw type and should not be used directly.
    Use ``SingleFailableN`` and ``DiverseFailableN`` instead.
    """

    __slots__ = ()

    _laws: ClassVar[Sequence[Law]] = (
        Law3(_FailableLawSpec.lash_short_circuit_law),
    )


#: Type alias for kinds with two type arguments.
Failable2 = FailableN[_FirstType, _SecondType, Never]

#: Type alias for kinds with three type arguments.
Failable3 = FailableN[_FirstType, _SecondType, _ThirdType]


@final
class _SingleFailableLawSpec(LawSpecDef):
    """
    Single Failable laws.

    We need to be sure that ``.map`` and ``.bind``
    works correctly for ``empty`` property.
    """

    __slots__ = ()

    @law_definition
    def map_short_circuit_law(
        container: 'SingleFailableN[_FirstType, _SecondType, _ThirdType]',
        function: Callable[[_FirstType], _NewFirstType],
    ) -> None:
        """Ensures that you cannot map from the `empty` property."""
        assert_equal(
            container.empty,
            container.empty.map(function),
        )

    @law_definition
    def bind_short_circuit_law(
        container: 'SingleFailableN[_FirstType, _SecondType, _ThirdType]',
        function: Callable[
            [_FirstType],
            KindN['SingleFailableN', _NewFirstType, _SecondType, _ThirdType],
        ],
    ) -> None:
        """Ensures that you cannot bind from the `empty` property."""
        assert_equal(
            container.empty,
            container.empty.bind(function),
        )

    @law_definition
    def apply_short_circuit_law(
        container: 'SingleFailableN[_FirstType, _SecondType, _ThirdType]',
        function: Callable[[_FirstType], _NewFirstType],
    ) -> None:
        """Ensures that you cannot apply from the `empty` property."""
        wrapped_function = container.from_value(function)
        assert_equal(
            container.empty,
            container.empty.apply(wrapped_function),
        )


class SingleFailableN(
    FailableN[_FirstType, _SecondType, _ThirdType],
):
    """
    Base type for types that have just only one failed value.

    Like ``Maybe`` types where the only failed value is ``Nothing``.
    """

    __slots__ = ()

    _laws: ClassVar[Sequence[Law]] = (
        Law2(_SingleFailableLawSpec.map_short_circuit_law),
        Law2(_SingleFailableLawSpec.bind_short_circuit_law),
        Law2(_SingleFailableLawSpec.apply_short_circuit_law),
    )

    @property
    @abstractmethod
    def empty(
        self: _SingleFailableType,
    ) -> 'SingleFailableN[_FirstType, _SecondType, _ThirdType]':
        """This property represents the failed value."""


#: Type alias for kinds with two types arguments.
SingleFailable2 = SingleFailableN[_FirstType, _SecondType, Never]

#: Type alias for kinds with three type arguments.
SingleFailable3 = SingleFailableN[_FirstType, _SecondType, _ThirdType]


@final
class _DiverseFailableLawSpec(LawSpecDef):
    """
    Diverse Failable laws.

    We need to be sure that ``.map``, ``.bind``, ``.apply`` and ``.alt``
    works correctly for both success and failure types.
    """

    __slots__ = ()

    @law_definition
    def map_short_circuit_law(
        raw_value: _SecondType,
        container: 'DiverseFailableN[_FirstType, _SecondType, _ThirdType]',
        function: Callable[[_FirstType], _NewFirstType],
    ) -> None:
        """Ensures that you cannot map a failure."""
        assert_equal(
            container.from_failure(raw_value),
            container.from_failure(raw_value).map(function),
        )

    @law_definition
    def bind_short_circuit_law(
        raw_value: _SecondType,
        container: 'DiverseFailableN[_FirstType, _SecondType, _ThirdType]',
        function: Callable[
            [_FirstType],
            KindN['DiverseFailableN', _NewFirstType, _SecondType, _ThirdType],
        ],
    ) -> None:
        """
        Ensures that you cannot bind a failure.

        See: https://wiki.haskell.org/Typeclassopedia#MonadFail
        """
        assert_equal(
            container.from_failure(raw_value),
            container.from_failure(raw_value).bind(function),
        )

    @law_definition
    def apply_short_circuit_law(
        raw_value: _SecondType,
        container: 'DiverseFailableN[_FirstType, _SecondType, _ThirdType]',
        function: Callable[[_FirstType], _NewFirstType],
    ) -> None:
        """Ensures that you cannot apply a failure."""
        wrapped_function = container.from_value(function)
        assert_equal(
            container.from_failure(raw_value),
            container.from_failure(raw_value).apply(wrapped_function),
        )

    @law_definition
    def alt_short_circuit_law(
        raw_value: _SecondType,
        container: 'DiverseFailableN[_FirstType, _SecondType, _ThirdType]',
        function: Callable[[_SecondType], _NewFirstType],
    ) -> None:
        """Ensures that you cannot alt a success."""
        assert_equal(
            container.from_value(raw_value),
            container.from_value(raw_value).alt(function),
        )


class DiverseFailableN(
    FailableN[_FirstType, _SecondType, _ThirdType],
    swappable.SwappableN[_FirstType, _SecondType, _ThirdType],
    Lawful['DiverseFailableN[_FirstType, _SecondType, _ThirdType]'],
):
    """
    Base type for types that have any failed value.

    Like ``Result`` types.
    """

    __slots__ = ()

    _laws: ClassVar[Sequence[Law]] = (
        Law3(_DiverseFailableLawSpec.map_short_circuit_law),
        Law3(_DiverseFailableLawSpec.bind_short_circuit_law),
        Law3(_DiverseFailableLawSpec.apply_short_circuit_law),
        Law3(_DiverseFailableLawSpec.alt_short_circuit_law),
    )

    @classmethod
    @abstractmethod
    def from_failure(
        cls: type[_DiverseFailableType],
        inner_value: _UpdatedType,
    ) -> KindN[_DiverseFailableType, _FirstType, _UpdatedType, _ThirdType]:
        """Unit method to create new containers from any raw value."""


#: Type alias for kinds with two type arguments.
DiverseFailable2 = DiverseFailableN[_FirstType, _SecondType, Never]

#: Type alias for kinds with three type arguments.
DiverseFailable3 = DiverseFailableN[_FirstType, _SecondType, _ThirdType]