Skip to content

❓ Option monad

fateful exposes a famous container for dealing with None or more generally speaking empty values (i.e. in python all instances of collections which are falsy).

It is called Optional. Basically, two classes derives from this base class, Some which represents a computed result which is not None or not falsy, and at the opposite Empty which is a wrapper of None or falsy values.

mypy compliant target

all the methods are typed to allow decent code completion

Examples

Let's take a look at the code and api to get the basis:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from fateful import opt

# optional is Some[str]
opt('value').or_else('new value')

# optional are mappable, returns VALUE
opt('value').map(str.upper).or_else("UNKNOWN")
none.map(str.upper).or_else("UNKOWN") # returns UNKNOWN

# will raise an error
opt(None).get() # same as none.get()

# optional are iterable
a = opt('optional option value')
for i in a:
    print(i)

Forwarding value

One funny thing is that you can forward a computation, like this

1
2
3
4
5
6
7
from fateful import opt
# forwarding value
class A:
    x = 5

opt(A()).x.or_else(0) # returns 5
opt(A()).y.or_else(0) # returns 0

Pattern matching on options

We also can use pattern matching:

1
2
3
4
5
6
from fateful import opt, Some, Empty, default

result = opt("value").match(
    Some(_) >> 1,
    default() >> 0
)

Real cases

In a real case example, it leads to this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def translate(value: str) -> str | None:
    if not value:
        return "world"
    if value == 'hello':
        return ', world'
    elif value == 'world':
        return ""
    return None

value = translate("Marco")
opt(value).map(

Lift known function to handle optional

1
2
3
4
5
6
7
8
9
from fateful import lift_opt

# function which throws an error
def divide(a, b):
    return a / b

lifted_fn = lift_opt(divide)

val  = lifted_fn(1, 0).or_else(0)

💻 API reference

Empty dataclass

Bases: OptionContainer[None]

Source code in fateful/monad/option.py
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
@dataclass(unsafe_hash=True)
class Empty(OptionContainer[None]):
    """ """

    _under: None = None

    def get(self) -> t.NoReturn:
        """
        Raise an EmptyError.

        Raises:
            EmptyError: because of getting on empty container.

        Returns:
            t.NoReturn: never returns.
        """
        raise EmptyError("Option is empty")

    def is_some(self) -> bool:
        """
        Return False.

        Returns:
            bool: always False.
        """
        return False

    def is_empty(self) -> bool:
        """
        Return True.

        Returns:
            bool: always True.
        """
        return True

    def or_(self, obj: V) -> V:
        """
        Return the provided value.

        Args:
            obj (V): provided value.

        Returns:
            V: provided value.

        ```python
        x: Empty = Null
        assert x.or_(1) == 1
        ```
        """
        return obj

    def or_else(self, obj: t.Callable[P, V], *args: P.args, **kwargs: P.kwargs) -> V:
        """
        Apply a function to produce a result. Computed lazily.

        Args:
            obj (t.Callable[P, V]): function to apply.

        Returns:
            V: return the result of the function.

        ```python
        x: Empty = Null
        x.or_else(lambda: 1) == 1
        ```
        """
        return obj(*args, **kwargs)

    def or_if_falsy(self, obj: V) -> V:
        """
        Return the provided value.

        Args:
            obj (V): provided value.

        Returns:
            V: provided value.

        ```python
        x = Null
        assert x.or_if_falsy(1) == 1
        ```
        """
        return obj

    def or_else_if_falsy(
        self, obj: t.Callable[P, V], *args: P.args, **kwargs: P.kwargs
    ) -> V:
        """
        Apply a function to produce a result. Computed lazily.

        Args:
            obj (t.Callable[P, V]): function to apply.

        Returns:
            V: result of the function.

        ```python
        x = Null
        assert x.or_else_if_falsy(lambda x: 2**4, 1) == 1
        ```
        """
        x = obj(*args, **kwargs) if callable(obj) else obj
        return x

    def or_none(self) -> None:
        """
        Return None.

        Returns:
            None: None.

        ```python
        x = Null
        assert x.or_none() is None
        ```
        """
        return None

    def or_raise(self, exc: Exception | None = None) -> t.NoReturn:
        """
        Raise an exception.

        Args:
            exc (Exception | None, optional): Exception to be raised. Defaults to None.

        Raises:
            EmptyError: if no exception is provided.
            exc: if an exception is provided.

        Returns:
            t.NoReturn: never returns.

        ```python
        x = Null
        x.or_raise()  # raises EmptyError
        x.or_raise(ValueError())  # raises ValueError
        ```
        """
        if exc is None:
            raise EmptyError("Option is empty")
        raise exc

    def map(self, func: t.Callable[[t.Any], t.Any]) -> "Empty":
        """
        Return an empty container.

        Args:
            func (t.Callable[[t.Any], t.Any]): function to apply.

        Returns:
            Empty: an empty container.
        """
        return self

    def __iter__(self) -> "t.Iterator[Empty]":
        """
        Return an empty iterator.

        Returns:
            t.Iterator[Empty]: empty iterator.
        """
        return self

    def __next__(self):
        raise StopIteration()

    def __getattr__(self, name: str) -> "Empty":
        """
        Return an empty container.

        Args:
            name (str): name of the attribute.

        Returns:
            Empty: an empty container.
        """
        return self

    def __call__(self, *args: t.Any, **kwargs: t.Any) -> "Empty":
        """
        Return an empty container.

        Returns:
            Empty: return an empty container.
        """
        return self

    def __str__(self) -> str:
        return "<Empty>"

    def flatten(self) -> "Empty":
        """
        Flatten the container.

        Returns:
            Empty: return self
        """
        return self

__call__(*args, **kwargs)

Return an empty container.

Returns:

Name Type Description
Empty Empty

return an empty container.

Source code in fateful/monad/option.py
496
497
498
499
500
501
502
503
def __call__(self, *args: t.Any, **kwargs: t.Any) -> "Empty":
    """
    Return an empty container.

    Returns:
        Empty: return an empty container.
    """
    return self

__getattr__(name)

Return an empty container.

Parameters:

Name Type Description Default
name str

name of the attribute.

required

Returns:

Name Type Description
Empty Empty

an empty container.

Source code in fateful/monad/option.py
484
485
486
487
488
489
490
491
492
493
494
def __getattr__(self, name: str) -> "Empty":
    """
    Return an empty container.

    Args:
        name (str): name of the attribute.

    Returns:
        Empty: an empty container.
    """
    return self

__iter__()

Return an empty iterator.

Returns:

Type Description
t.Iterator[Empty]

t.Iterator[Empty]: empty iterator.

Source code in fateful/monad/option.py
472
473
474
475
476
477
478
479
def __iter__(self) -> "t.Iterator[Empty]":
    """
    Return an empty iterator.

    Returns:
        t.Iterator[Empty]: empty iterator.
    """
    return self

flatten()

Flatten the container.

Returns:

Name Type Description
Empty Empty

return self

Source code in fateful/monad/option.py
508
509
510
511
512
513
514
515
def flatten(self) -> "Empty":
    """
    Flatten the container.

    Returns:
        Empty: return self
    """
    return self

get()

Raise an EmptyError.

Raises:

Type Description
EmptyError

because of getting on empty container.

Returns:

Type Description
t.NoReturn

t.NoReturn: never returns.

Source code in fateful/monad/option.py
321
322
323
324
325
326
327
328
329
330
331
def get(self) -> t.NoReturn:
    """
    Raise an EmptyError.

    Raises:
        EmptyError: because of getting on empty container.

    Returns:
        t.NoReturn: never returns.
    """
    raise EmptyError("Option is empty")

is_empty()

Return True.

Returns:

Name Type Description
bool bool

always True.

Source code in fateful/monad/option.py
342
343
344
345
346
347
348
349
def is_empty(self) -> bool:
    """
    Return True.

    Returns:
        bool: always True.
    """
    return True

is_some()

Return False.

Returns:

Name Type Description
bool bool

always False.

Source code in fateful/monad/option.py
333
334
335
336
337
338
339
340
def is_some(self) -> bool:
    """
    Return False.

    Returns:
        bool: always False.
    """
    return False

map(func)

Return an empty container.

Parameters:

Name Type Description Default
func t.Callable[[t.Any], t.Any]

function to apply.

required

Returns:

Name Type Description
Empty Empty

an empty container.

Source code in fateful/monad/option.py
460
461
462
463
464
465
466
467
468
469
470
def map(self, func: t.Callable[[t.Any], t.Any]) -> "Empty":
    """
    Return an empty container.

    Args:
        func (t.Callable[[t.Any], t.Any]): function to apply.

    Returns:
        Empty: an empty container.
    """
    return self

or_(obj)

Return the provided value.

Parameters:

Name Type Description Default
obj V

provided value.

required

Returns:

Name Type Description
V V

provided value.

x: Empty = Null
assert x.or_(1) == 1
Source code in fateful/monad/option.py
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
def or_(self, obj: V) -> V:
    """
    Return the provided value.

    Args:
        obj (V): provided value.

    Returns:
        V: provided value.

    ```python
    x: Empty = Null
    assert x.or_(1) == 1
    ```
    """
    return obj

or_else(obj, *args, **kwargs)

Apply a function to produce a result. Computed lazily.

Parameters:

Name Type Description Default
obj t.Callable[P, V]

function to apply.

required

Returns:

Name Type Description
V V

return the result of the function.

x: Empty = Null
x.or_else(lambda: 1) == 1
Source code in fateful/monad/option.py
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
def or_else(self, obj: t.Callable[P, V], *args: P.args, **kwargs: P.kwargs) -> V:
    """
    Apply a function to produce a result. Computed lazily.

    Args:
        obj (t.Callable[P, V]): function to apply.

    Returns:
        V: return the result of the function.

    ```python
    x: Empty = Null
    x.or_else(lambda: 1) == 1
    ```
    """
    return obj(*args, **kwargs)

or_else_if_falsy(obj, *args, **kwargs)

Apply a function to produce a result. Computed lazily.

Parameters:

Name Type Description Default
obj t.Callable[P, V]

function to apply.

required

Returns:

Name Type Description
V V

result of the function.

x = Null
assert x.or_else_if_falsy(lambda x: 2**4, 1) == 1
Source code in fateful/monad/option.py
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
def or_else_if_falsy(
    self, obj: t.Callable[P, V], *args: P.args, **kwargs: P.kwargs
) -> V:
    """
    Apply a function to produce a result. Computed lazily.

    Args:
        obj (t.Callable[P, V]): function to apply.

    Returns:
        V: result of the function.

    ```python
    x = Null
    assert x.or_else_if_falsy(lambda x: 2**4, 1) == 1
    ```
    """
    x = obj(*args, **kwargs) if callable(obj) else obj
    return x

or_if_falsy(obj)

Return the provided value.

Parameters:

Name Type Description Default
obj V

provided value.

required

Returns:

Name Type Description
V V

provided value.

x = Null
assert x.or_if_falsy(1) == 1
Source code in fateful/monad/option.py
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
def or_if_falsy(self, obj: V) -> V:
    """
    Return the provided value.

    Args:
        obj (V): provided value.

    Returns:
        V: provided value.

    ```python
    x = Null
    assert x.or_if_falsy(1) == 1
    ```
    """
    return obj

or_none()

Return None.

Returns:

Name Type Description
None None

None.

x = Null
assert x.or_none() is None
Source code in fateful/monad/option.py
422
423
424
425
426
427
428
429
430
431
432
433
434
def or_none(self) -> None:
    """
    Return None.

    Returns:
        None: None.

    ```python
    x = Null
    assert x.or_none() is None
    ```
    """
    return None

or_raise(exc=None)

Raise an exception.

Parameters:

Name Type Description Default
exc Exception | None

Exception to be raised. Defaults to None.

None

Raises:

Type Description
EmptyError

if no exception is provided.

exc

if an exception is provided.

Returns:

Type Description
t.NoReturn

t.NoReturn: never returns.

x = Null
x.or_raise()  # raises EmptyError
x.or_raise(ValueError())  # raises ValueError
Source code in fateful/monad/option.py
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
def or_raise(self, exc: Exception | None = None) -> t.NoReturn:
    """
    Raise an exception.

    Args:
        exc (Exception | None, optional): Exception to be raised. Defaults to None.

    Raises:
        EmptyError: if no exception is provided.
        exc: if an exception is provided.

    Returns:
        t.NoReturn: never returns.

    ```python
    x = Null
    x.or_raise()  # raises EmptyError
    x.or_raise(ValueError())  # raises ValueError
    ```
    """
    if exc is None:
        raise EmptyError("Option is empty")
    raise exc

Some dataclass

Bases: OptionContainer[T_co]

Source code in fateful/monad/option.py
 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
@dataclass(unsafe_hash=True, frozen=True)
class Some(OptionContainer[T_co]):
    """ """

    _under: T_co

    def get(self) -> T_co:
        """
        get the value of the Some container

        Returns:
            T: value of the container

        ```python
        x: Some[int] = opt(1).get()
        assert Some(1).get() == 1

        x: Empty = Null
        x.get()  # raises EmptyError !


        ```
        """
        return self._under

    def is_some(self) -> bool:
        """
        Check if the container is a Some.

        Returns:
            bool: true if the container is a Some, false otherwise.

        ```python
        x: Some[int] = opt(1)
        assert x.is_some() == True

        y = Null
        assert y.is_some() == False
        ```
        """
        return True

    def is_empty(self) -> bool:
        """
        Check if the container is empty.

        Returns:
            bool: True if the container is empty, False otherwise.

         ```python
        x = Null
        assert x.is_empty() == True

        y = Some(1)
        assert y.is_empty() == False
        ```
        """
        return False

    @t.overload
    def flatten(self: "Nested[Empty]") -> "Empty":  # type: ignore[misc]
        ...

    @t.overload
    def flatten(self: "Nested[Q]") -> "Some[Q]":
        ...

    def flatten(self) -> "Some | Empty":
        """
        Flatten the container i.e. transform Some(Some(x)) into Some(x).

        Returns:
            Some | Empty: the flattened container.

        ```python
        x: Some[Some[int]] = Some(Some(1))
        y: Some[int] = x.flatten()  # Some(1)
        assert y == Some(1)

        z: Some[Some[Empty]] = Some(Some(Null))
        a = z.flatten()  # Empty
        assert a == Null
        ```
        """
        x = self._under
        while isinstance(x, (Some, Empty)):
            x = x._under  # type: ignore
        return opt(x)

    def or_(self, obj: t.Any) -> T_co:
        """
        Return the value of the container.
        Args:
            obj (t.Any): an object

        Returns:
            T_co: the value of the container.

        ```python
        x: Some[int] = opt(1)
        y = x.or_(2)  # 1
        assert y == 1

        z = Null
        assert z.or_(2) == 2
        ```
        """
        return self._under

    def or_else(self, obj: t.Callable[P, V], *args: P.args, **kwargs: P.kwargs) -> V:
        """
        Apply a function to the value of the container.
        Args:
            obj (t.Callable[P, t.Any]): _description_

        Returns:
            T: return the value of the container.

        ```python
        x: Some[int] = opt(1)
        assert x.or_else(lambda z: z + 100, 1) == 1

        y = Null
        assert x.or_else(lambda z: z + 100, 1) == 101
        ```
        """
        return t.cast(V, self._under)

    unwrap_or_else = or_else  # type: ignore[assignment]

    def or_if_falsy(self, obj: V) -> T_co | V:
        """
        Return the value of the container or provided value if it is falsy.

        Args:
            obj (V): value to return if the container is falsy.

        Returns:
            T_co | V: value of the container or provided value if it is falsy.

        ```python
        x: Some[int] = opt(0)
        assert x.or_if_falsy(1) == 1
        ```
        """
        return self._under or obj

    def or_else_if_falsy(
        self, obj: t.Callable[P, V], *args: P.args, **kwargs: P.kwargs
    ) -> T_co | V:
        """
        Apply a function to the value of the container if it is falsy.

        Args:
            obj (t.Callable[P, U]): function to apply if contained value is falsy.

        Returns:
            T | U: value of the container or result of the function if it is falsy.

        ```python
        x: Some[int] = opt(0)
        assert x.or_else_if_falsy(lambda x: x + 101, 1) == 101
        ```
        """
        return self._under or obj(*args, **kwargs)

    def or_none(self) -> T_co:
        """
        Return the value of the container if it is not None.

        Returns:
            T: returns the value of the container.

        ```python
        x: Some[int] = opt(0)
        assert x.or_none() == 0  # 0
        ```
        """
        return self._under

    def or_raise(self, exc: Exception | None = None) -> T_co:
        """
        Return the value of the container if it is not None.

        Args:
            exc (Exception | None, optional): Exception to raise. Defaults to None.

        Returns:
            T: the underlying value of the container.

        ```python
        x: Some[int] = opt(0)
        assert x.or_raise() == 0  # 0
        ```
        """
        return self._under

    def map(self, func: t.Callable[[T_co], V]) -> "Some[V]":
        """
        Apply a function to the value of the container.

        Args:
            func (t.Callable[[T], U]): function to apply on the underlying value.

        Returns:
            Some[V]: Some if the function returns a value

        ```python
        x: Some[int] = opt(0)
        assert x.map(lambda c: c + 1).get() == 1  # 1

        y: Some[str] = opt(1).map(lambda c: str(c))
        ```
        """
        result = func(self._under)
        opt_result = opt(result)
        return opt_result

    def __iter__(self) -> t.Generator[T_co, t.Any, None]:
        """
        Iterate over the value of the container.

        Yields:
            Iterator[t.Iterator[T]]: _description_

        ```python
        for i in opt(0):
            print(i)  # 0
        ```
        """
        yield self.flatten().get()

    def __getattr__(self, name: str) -> "Some | Empty | t.Callable":
        """
        Get an attribute of the value of the container.

        Args:
            name (str): name of the attribute.

        Returns:
            Some | Empty | t.Callable: Some if the attribute exists, Empty otherwise.

        ```python
        class Foo:
            foo: int = 1
        x: Some[Foo] = opt(Foo())
        x.foo.get() == 1
        assert x.bar.is_empty()  # True
        ```
        """
        try:
            attr = getattr(self._under, name)
        except AttributeError:
            return none
        if callable(attr):

            def wrapper(*args: t.Any, **kwargs: t.Any) -> "Some[t.Any] | Empty":
                return opt(attr(*args, **kwargs))

            return wrapper
        return opt(attr)

    def __str__(self) -> str:
        """
        Return the string representation of the container.

        Returns:
            str: a string representation of the container.

        ```python
        str(Some(1)) # "<Some 1>"
        ```
        """
        return f"<Some {str(self._under)}>"

__getattr__(name)

Get an attribute of the value of the container.

Parameters:

Name Type Description Default
name str

name of the attribute.

required

Returns:

Type Description
Some | Empty | t.Callable

Some | Empty | t.Callable: Some if the attribute exists, Empty otherwise.

class Foo:
    foo: int = 1
x: Some[Foo] = opt(Foo())
x.foo.get() == 1
assert x.bar.is_empty()  # True
Source code in fateful/monad/option.py
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
def __getattr__(self, name: str) -> "Some | Empty | t.Callable":
    """
    Get an attribute of the value of the container.

    Args:
        name (str): name of the attribute.

    Returns:
        Some | Empty | t.Callable: Some if the attribute exists, Empty otherwise.

    ```python
    class Foo:
        foo: int = 1
    x: Some[Foo] = opt(Foo())
    x.foo.get() == 1
    assert x.bar.is_empty()  # True
    ```
    """
    try:
        attr = getattr(self._under, name)
    except AttributeError:
        return none
    if callable(attr):

        def wrapper(*args: t.Any, **kwargs: t.Any) -> "Some[t.Any] | Empty":
            return opt(attr(*args, **kwargs))

        return wrapper
    return opt(attr)

__iter__()

Iterate over the value of the container.

Yields:

Type Description
T_co

Iterator[t.Iterator[T]]: description

for i in opt(0):
    print(i)  # 0
Source code in fateful/monad/option.py
257
258
259
260
261
262
263
264
265
266
267
268
269
def __iter__(self) -> t.Generator[T_co, t.Any, None]:
    """
    Iterate over the value of the container.

    Yields:
        Iterator[t.Iterator[T]]: _description_

    ```python
    for i in opt(0):
        print(i)  # 0
    ```
    """
    yield self.flatten().get()

__str__()

Return the string representation of the container.

Returns:

Name Type Description
str str

a string representation of the container.

str(Some(1)) # "<Some 1>"
Source code in fateful/monad/option.py
301
302
303
304
305
306
307
308
309
310
311
312
def __str__(self) -> str:
    """
    Return the string representation of the container.

    Returns:
        str: a string representation of the container.

    ```python
    str(Some(1)) # "<Some 1>"
    ```
    """
    return f"<Some {str(self._under)}>"

flatten()

Flatten the container i.e. transform Some(Some(x)) into Some(x).

Returns:

Type Description
Some | Empty

Some | Empty: the flattened container.

x: Some[Some[int]] = Some(Some(1))
y: Some[int] = x.flatten()  # Some(1)
assert y == Some(1)

z: Some[Some[Empty]] = Some(Some(Null))
a = z.flatten()  # Empty
assert a == Null
Source code in fateful/monad/option.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def flatten(self) -> "Some | Empty":
    """
    Flatten the container i.e. transform Some(Some(x)) into Some(x).

    Returns:
        Some | Empty: the flattened container.

    ```python
    x: Some[Some[int]] = Some(Some(1))
    y: Some[int] = x.flatten()  # Some(1)
    assert y == Some(1)

    z: Some[Some[Empty]] = Some(Some(Null))
    a = z.flatten()  # Empty
    assert a == Null
    ```
    """
    x = self._under
    while isinstance(x, (Some, Empty)):
        x = x._under  # type: ignore
    return opt(x)

get()

get the value of the Some container

Returns:

Name Type Description
T T_co

value of the container

x: Some[int] = opt(1).get()
assert Some(1).get() == 1

x: Empty = Null
x.get()  # raises EmptyError !
Source code in fateful/monad/option.py
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def get(self) -> T_co:
    """
    get the value of the Some container

    Returns:
        T: value of the container

    ```python
    x: Some[int] = opt(1).get()
    assert Some(1).get() == 1

    x: Empty = Null
    x.get()  # raises EmptyError !


    ```
    """
    return self._under

is_empty()

Check if the container is empty.

Returns:

Name Type Description
bool bool

True if the container is empty, False otherwise.

```python x = Null assert x.is_empty() == True

y = Some(1) assert y.is_empty() == False ```

Source code in fateful/monad/option.py
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
def is_empty(self) -> bool:
    """
    Check if the container is empty.

    Returns:
        bool: True if the container is empty, False otherwise.

     ```python
    x = Null
    assert x.is_empty() == True

    y = Some(1)
    assert y.is_empty() == False
    ```
    """
    return False

is_some()

Check if the container is a Some.

Returns:

Name Type Description
bool bool

true if the container is a Some, false otherwise.

x: Some[int] = opt(1)
assert x.is_some() == True

y = Null
assert y.is_some() == False
Source code in fateful/monad/option.py
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
def is_some(self) -> bool:
    """
    Check if the container is a Some.

    Returns:
        bool: true if the container is a Some, false otherwise.

    ```python
    x: Some[int] = opt(1)
    assert x.is_some() == True

    y = Null
    assert y.is_some() == False
    ```
    """
    return True

map(func)

Apply a function to the value of the container.

Parameters:

Name Type Description Default
func t.Callable[[T], U]

function to apply on the underlying value.

required

Returns:

Type Description
Some[V]

Some[V]: Some if the function returns a value

x: Some[int] = opt(0)
assert x.map(lambda c: c + 1).get() == 1  # 1

y: Some[str] = opt(1).map(lambda c: str(c))
Source code in fateful/monad/option.py
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
def map(self, func: t.Callable[[T_co], V]) -> "Some[V]":
    """
    Apply a function to the value of the container.

    Args:
        func (t.Callable[[T], U]): function to apply on the underlying value.

    Returns:
        Some[V]: Some if the function returns a value

    ```python
    x: Some[int] = opt(0)
    assert x.map(lambda c: c + 1).get() == 1  # 1

    y: Some[str] = opt(1).map(lambda c: str(c))
    ```
    """
    result = func(self._under)
    opt_result = opt(result)
    return opt_result

or_(obj)

Return the value of the container.

Parameters:

Name Type Description Default
obj t.Any

an object

required

Returns:

Name Type Description
T_co T_co

the value of the container.

x: Some[int] = opt(1)
y = x.or_(2)  # 1
assert y == 1

z = Null
assert z.or_(2) == 2
Source code in fateful/monad/option.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
def or_(self, obj: t.Any) -> T_co:
    """
    Return the value of the container.
    Args:
        obj (t.Any): an object

    Returns:
        T_co: the value of the container.

    ```python
    x: Some[int] = opt(1)
    y = x.or_(2)  # 1
    assert y == 1

    z = Null
    assert z.or_(2) == 2
    ```
    """
    return self._under

or_else(obj, *args, **kwargs)

Apply a function to the value of the container.

Parameters:

Name Type Description Default
obj t.Callable[P, t.Any]

description

required

Returns:

Name Type Description
T V

return the value of the container.

x: Some[int] = opt(1)
assert x.or_else(lambda z: z + 100, 1) == 1

y = Null
assert x.or_else(lambda z: z + 100, 1) == 101
Source code in fateful/monad/option.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
def or_else(self, obj: t.Callable[P, V], *args: P.args, **kwargs: P.kwargs) -> V:
    """
    Apply a function to the value of the container.
    Args:
        obj (t.Callable[P, t.Any]): _description_

    Returns:
        T: return the value of the container.

    ```python
    x: Some[int] = opt(1)
    assert x.or_else(lambda z: z + 100, 1) == 1

    y = Null
    assert x.or_else(lambda z: z + 100, 1) == 101
    ```
    """
    return t.cast(V, self._under)

or_else_if_falsy(obj, *args, **kwargs)

Apply a function to the value of the container if it is falsy.

Parameters:

Name Type Description Default
obj t.Callable[P, U]

function to apply if contained value is falsy.

required

Returns:

Type Description
T_co | V

T | U: value of the container or result of the function if it is falsy.

x: Some[int] = opt(0)
assert x.or_else_if_falsy(lambda x: x + 101, 1) == 101
Source code in fateful/monad/option.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
def or_else_if_falsy(
    self, obj: t.Callable[P, V], *args: P.args, **kwargs: P.kwargs
) -> T_co | V:
    """
    Apply a function to the value of the container if it is falsy.

    Args:
        obj (t.Callable[P, U]): function to apply if contained value is falsy.

    Returns:
        T | U: value of the container or result of the function if it is falsy.

    ```python
    x: Some[int] = opt(0)
    assert x.or_else_if_falsy(lambda x: x + 101, 1) == 101
    ```
    """
    return self._under or obj(*args, **kwargs)

or_if_falsy(obj)

Return the value of the container or provided value if it is falsy.

Parameters:

Name Type Description Default
obj V

value to return if the container is falsy.

required

Returns:

Type Description
T_co | V

T_co | V: value of the container or provided value if it is falsy.

x: Some[int] = opt(0)
assert x.or_if_falsy(1) == 1
Source code in fateful/monad/option.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def or_if_falsy(self, obj: V) -> T_co | V:
    """
    Return the value of the container or provided value if it is falsy.

    Args:
        obj (V): value to return if the container is falsy.

    Returns:
        T_co | V: value of the container or provided value if it is falsy.

    ```python
    x: Some[int] = opt(0)
    assert x.or_if_falsy(1) == 1
    ```
    """
    return self._under or obj

or_none()

Return the value of the container if it is not None.

Returns:

Name Type Description
T T_co

returns the value of the container.

x: Some[int] = opt(0)
assert x.or_none() == 0  # 0
Source code in fateful/monad/option.py
205
206
207
208
209
210
211
212
213
214
215
216
217
def or_none(self) -> T_co:
    """
    Return the value of the container if it is not None.

    Returns:
        T: returns the value of the container.

    ```python
    x: Some[int] = opt(0)
    assert x.or_none() == 0  # 0
    ```
    """
    return self._under

or_raise(exc=None)

Return the value of the container if it is not None.

Parameters:

Name Type Description Default
exc Exception | None

Exception to raise. Defaults to None.

None

Returns:

Name Type Description
T T_co

the underlying value of the container.

x: Some[int] = opt(0)
assert x.or_raise() == 0  # 0
Source code in fateful/monad/option.py
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
def or_raise(self, exc: Exception | None = None) -> T_co:
    """
    Return the value of the container if it is not None.

    Args:
        exc (Exception | None, optional): Exception to raise. Defaults to None.

    Returns:
        T: the underlying value of the container.

    ```python
    x: Some[int] = opt(0)
    assert x.or_raise() == 0  # 0
    ```
    """
    return self._under