Skip to content

Useful functions

💻 API reference

Default dataclass

Bases: t.Generic[V]

Default value for pattern matching.

Parameters:

Name Type Description Default
t _type_

description

required
Source code in fateful/monad/func.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
@dataclass
class Default(t.Generic[V]):
    """
    Default value for pattern matching.

    Args:
        t (_type_): _description_
    """

    def __init__(self):
        self.action: t.Callable[[], V] | V | None = None

    def __rshift__(self, other: t.Callable[[], T] | T) -> "Default[T]":
        default: Default[T] = Default()
        default.action = other
        return default

MatchError

Bases: TypeError

Raised when a match is not found.

Source code in fateful/monad/func.py
48
49
50
51
52
53
class MatchError(TypeError):
    """
    Raised when a match is not found.
    """

    ...

MatchableMixin

Bases: t.Generic[T_co]

Mixin class for pattern matching.

Parameters:

Name Type Description Default
t _type_

description

required

Raises:

Type Description
MatchError

description

MatchError

description

Returns:

Name Type Description
_type_

description

Source code in fateful/monad/func.py
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
class MatchableMixin(t.Generic[T_co]):
    """
    Mixin class for pattern matching.

    Args:
        t (_type_): _description_

    Raises:
        MatchError: _description_
        MatchError: _description_

    Returns:
        _type_: _description_
    """

    __matchable_classes__: t.ClassVar[set[t.Any]] = set()

    @t.overload
    def __rshift__(
        self: "MatchableMixin[UnderscoreType]", other: t.Callable[[T_co], T_co]
    ) -> When[T, T]:
        ...

    @t.overload
    def __rshift__(self: "MatchableMixin[V]", other: t.Callable[[V], U]) -> When[V, U]:
        ...

    @t.overload
    def __rshift__(
        self: "MatchableMixin[T_co]", other: t.Callable[[T_co], U]
    ) -> When[T_co, U]:
        ...

    def __rshift__(self, other: t.Callable) -> When:
        """ """
        return When(self).then(other)

    @t.overload
    def match(
        self: "Nested[T]",
        *whens: "When[Nested[UnderscoreType], Nested[UnderscoreType]]  | Default[T]",
    ) -> T:
        ...

    @t.overload
    def match(self, *whens: When[UnderscoreType, UnderscoreType]) -> T_co:
        """
        >>> v = opt(1).match(Ok(_under=_) >> identity)
        """
        ...

    @t.overload
    def match(self, *whens: When[UnderscoreType, Q] | Default[t.Any]) -> Q:
        """
        >>> value.match(
        >>>    when(Some(_)).then(lambda x: "match first"),
        >>>    when(Some(_)).then(lambda x: x * 2),
        >>>    default >> (partial(raise_error, MatchError())),
        >>> )
        or
        >>> k = opt(1).match(Some(_) >> (lambda x: str(x)))
        """
        ...

    @t.overload
    def match(self, *whens: When[T_co, T_co] | Default[T_co]) -> T_co:
        """
        >>> opt(1).match(Some(2) >> identity, default >> (lambda: 100))
        """
        ...

    @t.overload
    def match(self, *whens: When[T_co, Q] | Default[V]) -> Q | V:
        """
        >>> opt(1).match(
                *(Some(_under=2) >> (lambda x: str(x)),
                (default >> (lambda: 100)))
            )
        """
        ...

    @t.overload
    def match(self, *whens: "MatchableMixin[UnderscoreType]" | Default[T_co]) -> T_co:
        """
        >>> d = opt(1).match(*(Some(_), default >>  100))
        """
        ...

    @t.overload
    def match(self, *whens: "MatchableMixin[V]") -> V:
        """
        >>> val = opt(ValueError).match(Some(type[ValueError]))
        """
        ...

    @t.overload
    def match(self, *whens: "MatchableMixin[t.Any]" | Default[V]) -> V | t.Any:
        """
        >>> m1, m2 = val.match(*(Some({1: _, 2: _}), default >> (1, 2)))
        """
        ...

    @t.overload
    def match(self, *whens: "When | MatchableMixin | Default") -> t.Any:
        """
        Can not infer other return type !
        """
        ...

    def match(
        self, *whens: "When[t.Any, t.Any] | MatchableMixin[t.Any] | Default[t.Any]"
    ) -> t.Any:
        for w in whens:
            if isinstance(w, Default):
                assert w.action is not None
                return w.action()

            when_inst = w
            if not isinstance(when_inst, When):
                # assert isinstance(when_inst, Matchable)
                when_inst = When(when_inst)

            if isinstance(when_inst, when):
                clazz = when_inst.value.__class__

                if clazz not in self.__matchable_classes__:
                    raise MatchError(
                        f"Incompatible match class found: {when_inst.value} "
                        f"not in {self.__matchable_classes__}"
                    )

                if clazz == self.__class__:
                    match_dict, self_dict = convert_to_dict(
                        when_inst.value.__dict__
                    ), convert_to_dict(self.__dict__)
                    is_a_match, extracted = pampy_dict_matcher(match_dict, self_dict)
                    if not is_a_match:
                        continue
                    if when_inst.action is None:
                        if len(extracted) == 1:
                            return extracted[0]
                        return extracted
                    return when_inst.action(*extracted)
        raise MatchError(f"No default guard found, enable to match {self}")

When

Bases: t.Generic[T_co, S_co]

Dealing with pattern matching in a functional way.

Source code in fateful/monad/func.py
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
class When(t.Generic[T_co, S_co]):
    """
    Dealing with pattern matching in a functional way.
    """

    def __init__(self, value: "MatchableMixin[T_co]"):
        self.value = value
        self.action: t.Callable[..., S_co] | None = None

    def then(self, f: t.Callable[..., Q]) -> "When[T_co, Q]":
        """ """
        when: When[T_co, Q] = When(self.value)
        when.action = f
        return when

    def __repr__(self):
        return repr(self.value)

convert_to_dict(obj)

convert a dataclass to a dict without deep copying it

Parameters:

Name Type Description Default
obj dict[str, t.Any]

description

required

Returns:

Type Description
dict[str, t.Any]

dict[str, t.Any]: description

Source code in fateful/monad/func.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
def convert_to_dict(obj: dict[str, t.Any]) -> dict[str, t.Any]:
    """
    convert a dataclass to a dict without deep copying it

    Args:
        obj (dict[str, t.Any]): _description_

    Returns:
        dict[str, t.Any]: _description_
    """
    for key, value in obj.items():
        if dataclasses.is_dataclass(value):
            obj[key] = value.__dict__
            convert_to_dict(obj[key])
    return obj

identity(x)

identity function

Source code in fateful/monad/func.py
14
15
16
17
18
def identity(x: T) -> T:
    """
    identity function
    """
    return x

raise_err(err)

return a function that raises an error

Parameters:

Name Type Description Default
err _type_

description

required
Source code in fateful/monad/func.py
21
22
23
24
25
26
27
28
29
30
31
32
def raise_err(err):
    """
    return a function that raises an error

    Args:
        err (_type_): _description_
    """

    def inner():
        raise err

    return inner

raise_error(error)

raise an error directly

Parameters:

Name Type Description Default
error Exception

description

required

Raises:

Type Description
error

description

Source code in fateful/monad/func.py
35
36
37
38
39
40
41
42
43
44
45
def raise_error(error: Exception):  # pragma: no cover
    """
    raise an error directly

    Args:
        error (Exception): _description_

    Raises:
        error: _description_
    """
    raise error