Skip to content

Err

Bases: Result[T, E]

Represents an error value.

Attributes:

Name Type Description
error E

The contained error value.

Source code in src/pyochain/_results/_result.py
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
@dataclass(slots=True)
class Err[T, E](Result[T, E]):
    """Represents an error value.

    Attributes:
        error (E): The contained error value.
    """

    error: E

    def __repr__(self) -> str:
        return f"Err({self.error!r})"

    def is_ok(self) -> bool:
        return False

    def is_err(self) -> bool:
        return True

    def unwrap(self) -> Never:
        msg = f"called `unwrap` on Err: {self.error!r}"
        raise ResultUnwrapError(msg)

    def unwrap_err(self) -> E:
        return self.error

error instance-attribute

error: E

and_

and_(res: Result[U, E]) -> Result[U, E]

Returns res if the result is Ok, otherwise returns the Err value.

This is often used for chaining operations that might fail.

Parameters:

Name Type Description Default
res Result[U, E]

The result to return if the original result is Ok.

required

Returns:

Type Description
Result[U, E]

Result[U, E]: res if the original result is Ok, otherwise the original Err.

Example:

>>> import pyochain as pc
>>> x = pc.Ok(2)
>>> y = pc.Err("late error")
>>> x.and_(y)
Err('late error')
>>> x = pc.Err("early error")
>>> y = pc.Ok("foo")
>>> x.and_(y)
Err('early error')

>>> x = pc.Err("not a 2")
>>> y = pc.Err("late error")
>>> x.and_(y)
Err('not a 2')

>>> x = pc.Ok(2)
>>> y = pc.Ok("different result type")
>>> x.and_(y)
Ok('different result type')

Source code in src/pyochain/_results/_result.py
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
def and_[U](self, res: Result[U, E]) -> Result[U, E]:
    """Returns `res` if the result is `Ok`, otherwise returns the `Err` value.

    This is often used for chaining operations that might fail.

    Args:
        res (Result[U, E]): The result to return if the original result is `Ok`.

    Returns:
        Result[U, E]: `res` if the original result is `Ok`, otherwise the original `Err`.

    Example:
    ```python
    >>> import pyochain as pc
    >>> x = pc.Ok(2)
    >>> y = pc.Err("late error")
    >>> x.and_(y)
    Err('late error')
    >>> x = pc.Err("early error")
    >>> y = pc.Ok("foo")
    >>> x.and_(y)
    Err('early error')

    >>> x = pc.Err("not a 2")
    >>> y = pc.Err("late error")
    >>> x.and_(y)
    Err('not a 2')

    >>> x = pc.Ok(2)
    >>> y = pc.Ok("different result type")
    >>> x.and_(y)
    Ok('different result type')

    ```
    """
    return res if self.is_ok() else cast(Result[U, E], self)

and_then

and_then(
    fn: Callable[Concatenate[T, P], Result[R, E]], *args: P.args, **kwargs: P.kwargs
) -> Result[R, E]

Calls a function if the result is Ok, otherwise returns the Err value.

This is often used for chaining operations that might fail.

Parameters:

Name Type Description Default
fn Callable[Concatenate[T, P], Result[R, E]]

The function to call with the Ok value.

required
*args P.args

Additional positional arguments to pass to fn.

()
**kwargs P.kwargs

Additional keyword arguments to pass to fn.

{}

Returns:

Type Description
Result[R, E]

Result[R, E]: The result of the function if Ok, otherwise the original Err.

Example:

>>> import pyochain as pc
>>> def to_str(x: int) -> Result[str, str]:
...     return pc.Ok(str(x))
>>> pc.Ok(2).and_then(to_str)
Ok('2')
>>> pc.Err("error").and_then(to_str)
Err('error')

Source code in src/pyochain/_results/_result.py
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
def and_then[**P, R](
    self,
    fn: Callable[Concatenate[T, P], Result[R, E]],
    *args: P.args,
    **kwargs: P.kwargs,
) -> Result[R, E]:
    """Calls a function if the result is `Ok`, otherwise returns the `Err` value.

    This is often used for chaining operations that might fail.

    Args:
        fn (Callable[Concatenate[T, P], Result[R, E]]): The function to call with the `Ok` value.
        *args (P.args): Additional positional arguments to pass to fn.
        **kwargs (P.kwargs): Additional keyword arguments to pass to fn.

    Returns:
        Result[R, E]: The result of the function if `Ok`, otherwise the original `Err`.

    Example:
    ```python
    >>> import pyochain as pc
    >>> def to_str(x: int) -> Result[str, str]:
    ...     return pc.Ok(str(x))
    >>> pc.Ok(2).and_then(to_str)
    Ok('2')
    >>> pc.Err("error").and_then(to_str)
    Err('error')

    ```
    """
    return (
        fn(self.unwrap(), *args, **kwargs)
        if self.is_ok()
        else cast(Result[R, E], self)
    )

err

err() -> Option[E]

Converts from Result[T, E] to Option[E].

Err(e) becomes Some(e), and Ok(v) becomes None.

Returns:

Type Description
Option[E]

Option[E]: An Option containing the Err value, or None if the result is Ok.

Example:

>>> import pyochain as pc
>>> pc.Ok(2).err()
NONE
>>> pc.Err("error").err()
Some('error')

Source code in src/pyochain/_results/_result.py
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
def err(self) -> Option[E]:
    """Converts from `Result[T, E]` to `Option[E]`.

    `Err(e)` becomes `Some(e)`, and `Ok(v)` becomes `None`.

    Returns:
        Option[E]: An `Option` containing the `Err` value, or `None` if the result is `Ok`.

    Example:
    ```python
    >>> import pyochain as pc
    >>> pc.Ok(2).err()
    NONE
    >>> pc.Err("error").err()
    Some('error')

    ```
    """
    from ._option import NONE, Some

    return Some(self.unwrap_err()) if self.is_err() else NONE

expect

expect(msg: str) -> T

Returns the contained Ok value.

Raises an exception with a provided message if the value is an Err.

Parameters:

Name Type Description Default
msg str

The message to include in the exception if the result is Err.

required

Returns:

Name Type Description
T T

The contained Ok value.

Raises:

Type Description
ResultUnwrapError

If the result is Err.

Example:

>>> import pyochain as pc
>>> pc.Ok(2).expect("No error")
2
>>> pc.Err("emergency failure").expect("Testing expect")
Traceback (most recent call last):
    ...
pyochain._results._result.ResultUnwrapError: Testing expect: emergency failure

Source code in src/pyochain/_results/_result.py
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
def expect(self, msg: str) -> T:
    """Returns the contained `Ok` value.

    Raises an exception with a provided message if the value is an `Err`.

    Args:
        msg (str): The message to include in the exception if the result is `Err`.

    Returns:
        T: The contained `Ok` value.

    Raises:
        ResultUnwrapError: If the result is `Err`.

    Example:
    ```python
    >>> import pyochain as pc
    >>> pc.Ok(2).expect("No error")
    2
    >>> pc.Err("emergency failure").expect("Testing expect")
    Traceback (most recent call last):
        ...
    pyochain._results._result.ResultUnwrapError: Testing expect: emergency failure

    ```
    """
    if self.is_ok():
        return self.unwrap()
    err_msg = f"{msg}: {self.unwrap_err()}"
    raise ResultUnwrapError(err_msg)

expect_err

expect_err(msg: str) -> E

Returns the contained Err value.

Raises an exception with a provided message if the value is an Ok.

Parameters:

Name Type Description Default
msg str

The message to include in the exception if the result is Ok.

required

Returns:

Name Type Description
E E

The contained Err value.

Raises:

Type Description
ResultUnwrapError

If the result is Ok.

Example:

>>> import pyochain as pc
>>> pc.Err("emergency failure").expect_err("Testing expect_err")
'emergency failure'
>>> pc.Ok(10).expect_err("Testing expect_err")
Traceback (most recent call last):
    ...
pyochain._results._result.ResultUnwrapError: Testing expect_err: expected Err, got Ok(10)

Source code in src/pyochain/_results/_result.py
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
def expect_err(self, msg: str) -> E:
    """Returns the contained `Err` value.

    Raises an exception with a provided message if the value is an `Ok`.

    Args:
        msg (str): The message to include in the exception if the result is `Ok`.

    Returns:
        E: The contained `Err` value.

    Raises:
        ResultUnwrapError: If the result is `Ok`.

    Example:
    ```python
    >>> import pyochain as pc
    >>> pc.Err("emergency failure").expect_err("Testing expect_err")
    'emergency failure'
    >>> pc.Ok(10).expect_err("Testing expect_err")
    Traceback (most recent call last):
        ...
    pyochain._results._result.ResultUnwrapError: Testing expect_err: expected Err, got Ok(10)

    ```
    """
    if self.is_err():
        return self.unwrap_err()
    err_msg = f"{msg}: expected Err, got Ok({self.unwrap()!r})"
    raise ResultUnwrapError(err_msg)

flatten

flatten() -> Result[T, E]

Flattens a nested Result.

Converts from Result[Result[T, E], E] to Result[T, E].

Equivalent to calling Result.and_then(lambda x: x), but more convenient when there's no need to process the inner Ok value.

Returns:

Type Description
Result[T, E]

Result[T, E]: The flattened result.

Example:

>>> import pyochain as pc
>>> nested_ok: pc.Result[pc.Result[int, str], str] = pc.Ok(pc.Ok(2))
>>> nested_ok.flatten()
Ok(2)
>>> nested_err: pc.Result[pc.Result[int, str], str] = pc.Ok(pc.Err("inner error"))
>>> nested_err.flatten()
Err('inner error')

Source code in src/pyochain/_results/_result.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
def flatten(self: Result[Result[T, E], E]) -> Result[T, E]:
    """Flattens a nested `Result`.

    Converts from `Result[Result[T, E], E]` to `Result[T, E]`.

    Equivalent to calling `Result.and_then(lambda x: x)`, but more convenient when there's no need to process the inner `Ok` value.

    Returns:
        Result[T, E]: The flattened result.

    Example:
    ```python
    >>> import pyochain as pc
    >>> nested_ok: pc.Result[pc.Result[int, str], str] = pc.Ok(pc.Ok(2))
    >>> nested_ok.flatten()
    Ok(2)
    >>> nested_err: pc.Result[pc.Result[int, str], str] = pc.Ok(pc.Err("inner error"))
    >>> nested_err.flatten()
    Err('inner error')

    ```
    """
    return self.and_then(lambda x: x)

inspect

inspect(
    fn: Callable[Concatenate[T, P], object], *args: P.args, **kwargs: P.kwargs
) -> Result[T, E]

Applies a function to the contained Ok value, returning the original Result.

This is primarily useful for debugging or logging, allowing side effects to be performed on the Ok value without changing the result.

Parameters:

Name Type Description Default
fn Callable[Concatenate[T, P], object]

Function to apply to the Ok value.

required
*args P.args

Additional positional arguments to pass to fn.

()
**kwargs P.kwargs

Additional keyword arguments to pass to fn.

{}

Returns:

Type Description
Result[T, E]

Result[T, E]: The original result, unchanged.

Example:

>>> import pyochain as pc
>>> seen: list[int] = []
>>> pc.Ok(2).inspect(lambda x: seen.append(x))
Ok(2)
>>> seen
[2]

Source code in src/pyochain/_results/_result.py
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
def inspect[**P](
    self, fn: Callable[Concatenate[T, P], object], *args: P.args, **kwargs: P.kwargs
) -> Result[T, E]:
    """Applies a function to the contained `Ok` value, returning the original `Result`.

    This is primarily useful for debugging or logging, allowing side effects to be
    performed on the `Ok` value without changing the result.

    Args:
        fn (Callable[Concatenate[T, P], object]): Function to apply to the `Ok` value.
        *args (P.args): Additional positional arguments to pass to fn.
        **kwargs (P.kwargs): Additional keyword arguments to pass to fn.

    Returns:
        Result[T, E]: The original result, unchanged.

    Example:
    ```python
    >>> import pyochain as pc
    >>> seen: list[int] = []
    >>> pc.Ok(2).inspect(lambda x: seen.append(x))
    Ok(2)
    >>> seen
    [2]

    ```
    """
    if self.is_ok():
        fn(self.unwrap(), *args, **kwargs)
    return self

inspect_err

inspect_err(
    fn: Callable[Concatenate[E, P], object], *args: P.args, **kwargs: P.kwargs
) -> Result[T, E]

Applies a function to the contained Err value, returning the original Result.

This mirrors :meth:inspect but operates on the error value. It is useful for logging or debugging error paths while keeping the Result unchanged.

Parameters:

Name Type Description Default
fn Callable[Concatenate[E, P], object]

Function to apply to the Err value.

required
*args P.args

Additional positional arguments to pass to fn.

()
**kwargs P.kwargs

Additional keyword arguments to pass to fn.

{}

Returns:

Type Description
Result[T, E]

Result[T, E]: The original result, unchanged.

Example:

>>> import pyochain as pc
>>> seen: list[str] = []
>>> pc.Err("oops").inspect_err(lambda e: seen.append(e))
Err('oops')
>>> seen
['oops']

Source code in src/pyochain/_results/_result.py
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
def inspect_err[**P](
    self, fn: Callable[Concatenate[E, P], object], *args: P.args, **kwargs: P.kwargs
) -> Result[T, E]:
    """Applies a function to the contained `Err` value, returning the original `Result`.

    This mirrors :meth:`inspect` but operates on the error value. It is useful for
    logging or debugging error paths while keeping the `Result` unchanged.

    Args:
        fn (Callable[Concatenate[E, P], object]): Function to apply to the `Err` value.
        *args (P.args): Additional positional arguments to pass to fn.
        **kwargs (P.kwargs): Additional keyword arguments to pass to fn.

    Returns:
        Result[T, E]: The original result, unchanged.

    Example:
    ```python
    >>> import pyochain as pc
    >>> seen: list[str] = []
    >>> pc.Err("oops").inspect_err(lambda e: seen.append(e))
    Err('oops')
    >>> seen
    ['oops']

    ```
    """
    if self.is_err():
        fn(self.unwrap_err(), *args, **kwargs)
    return self

into

into(func: Callable[Concatenate[Self, P], R], *args: P.args, **kwargs: P.kwargs) -> R

Convert Self to R.

This method allows to pipe the instance into an object or function that can convert Self into another type.

Conceptually, this allow to do x.into(f) instead of f(x), hence keeping a functional chaining style.

This is a core method, shared by all pyochain wrappers, that allows chaining operations in a functional style.

Parameters:

Name Type Description Default
func Callable[Concatenate[Self, P], R]

Function for conversion.

required
*args P.args

Positional arguments to pass to the function.

()
**kwargs P.kwargs

Keyword arguments to pass to the function.

{}

Returns:

Name Type Description
R R

The converted value.

Example:

>>> import pyochain as pc
>>> def maybe_sum(data: pc.Seq[int]) -> pc.Option[int]:
...     match data.length():
...         case 0:
...             return pc.NONE
...         case _:
...             return pc.Some(data.sum())
>>>
>>> pc.Seq(range(5)).into(maybe_sum).unwrap()
10

Source code in src/pyochain/_core/_main.py
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
def into[**P, R](
    self,
    func: Callable[Concatenate[Self, P], R],
    *args: P.args,
    **kwargs: P.kwargs,
) -> R:
    """Convert `Self` to `R`.

    This method allows to pipe the instance into an object or function that can convert `Self` into another type.

    Conceptually, this allow to do x.into(f) instead of f(x), hence keeping a functional chaining style.

    This is a core method, shared by all pyochain wrappers, that allows chaining operations in a functional style.

    Args:
        func (Callable[Concatenate[Self, P], R]): Function for conversion.
        *args (P.args): Positional arguments to pass to the function.
        **kwargs (P.kwargs): Keyword arguments to pass to the function.

    Returns:
        R: The converted value.

    Example:
    ```python
    >>> import pyochain as pc
    >>> def maybe_sum(data: pc.Seq[int]) -> pc.Option[int]:
    ...     match data.length():
    ...         case 0:
    ...             return pc.NONE
    ...         case _:
    ...             return pc.Some(data.sum())
    >>>
    >>> pc.Seq(range(5)).into(maybe_sum).unwrap()
    10

    ```
    """
    return func(self, *args, **kwargs)

is_err

is_err() -> bool
Source code in src/pyochain/_results/_result.py
769
770
def is_err(self) -> bool:
    return True

is_err_and

is_err_and(
    pred: Callable[Concatenate[E, P], bool], *args: P.args, **kwargs: P.kwargs
) -> bool

Returns True if the result is Err and the predicate is true for the error value.

Parameters:

Name Type Description Default
pred Callable[Concatenate[E, P], bool]

Predicate function to apply to the Err value.

required
*args P.args

Additional positional arguments to pass to pred.

()
**kwargs P.kwargs

Additional keyword arguments to pass to pred.

{}

Returns:

Name Type Description
bool bool

True if Err and pred(error) is true, False otherwise.

Example:

>>> import pyochain as pc
>>> pc.Err("foo").is_err_and(lambda e: len(e) == 3)
True
>>> pc.Err("bar").is_err_and(lambda e: e == "baz")
False
>>> pc.Ok(2).is_err_and(lambda e: True)
False

Source code in src/pyochain/_results/_result.py
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
def is_err_and[**P](
    self, pred: Callable[Concatenate[E, P], bool], *args: P.args, **kwargs: P.kwargs
) -> bool:
    """Returns True if the result is Err and the predicate is true for the error value.

    Args:
        pred (Callable[Concatenate[E, P], bool]): Predicate function to apply to the Err value.
        *args (P.args): Additional positional arguments to pass to pred.
        **kwargs (P.kwargs): Additional keyword arguments to pass to pred.

    Returns:
        bool: True if Err and pred(error) is true, False otherwise.

    Example:
    ```python
    >>> import pyochain as pc
    >>> pc.Err("foo").is_err_and(lambda e: len(e) == 3)
    True
    >>> pc.Err("bar").is_err_and(lambda e: e == "baz")
    False
    >>> pc.Ok(2).is_err_and(lambda e: True)
    False

    ```
    """
    return self.is_err() and pred(self.unwrap_err(), *args, **kwargs)

is_ok

is_ok() -> bool
Source code in src/pyochain/_results/_result.py
766
767
def is_ok(self) -> bool:
    return False

is_ok_and

is_ok_and(
    pred: Callable[Concatenate[T, P], bool], *args: P.args, **kwargs: P.kwargs
) -> bool

Returns True if the result is Ok and the predicate is true for the contained value.

Parameters:

Name Type Description Default
pred Callable[Concatenate[T, P], bool]

Predicate function to apply to the Ok value.

required
*args P.args

Additional positional arguments to pass to pred.

()
**kwargs P.kwargs

Additional keyword arguments to pass to pred.

{}

Returns:

Name Type Description
bool bool

True if Ok and pred(value) is true, False otherwise.

Example:

>>> import pyochain as pc
>>> pc.Ok(2).is_ok_and(lambda x: x > 1)
True
>>> pc.Ok(0).is_ok_and(lambda x: x > 1)
False
>>> pc.Err("err").is_ok_and(lambda x: x > 1)
False

Source code in src/pyochain/_results/_result.py
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
def is_ok_and[**P](
    self, pred: Callable[Concatenate[T, P], bool], *args: P.args, **kwargs: P.kwargs
) -> bool:
    """Returns True if the result is `Ok` and the predicate is true for the contained value.

    Args:
        pred (Callable[Concatenate[T, P], bool]): Predicate function to apply to the `Ok` value.
        *args (P.args): Additional positional arguments to pass to pred.
        **kwargs (P.kwargs): Additional keyword arguments to pass to pred.

    Returns:
        bool: True if `Ok` and pred(value) is true, False otherwise.

    Example:
    ```python
    >>> import pyochain as pc
    >>> pc.Ok(2).is_ok_and(lambda x: x > 1)
    True
    >>> pc.Ok(0).is_ok_and(lambda x: x > 1)
    False
    >>> pc.Err("err").is_ok_and(lambda x: x > 1)
    False

    ```
    """
    return self.is_ok() and pred(self.unwrap(), *args, **kwargs)

iter

iter() -> Iter[T]

Returns a Iter[T] over the possibly contained value.

The iterator yields one value if the result is Ok, otherwise none.

Returns:

Type Description
Iter[T]

Iter[T]: An iterator over the Ok value, or empty if Err.

Examples:

>>> import pyochain as pc
>>> pc.Ok(7).iter().next()
Some(7)
>>> pc.Err("nothing!").iter().next()
NONE

Source code in src/pyochain/_results/_result.py
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
def iter(self) -> Iter[T]:
    """Returns a `Iter[T]` over the possibly contained value.

    The iterator yields one value if the result is `Ok`, otherwise none.

    Returns:
        Iter[T]: An iterator over the `Ok` value, or empty if `Err`.

    Examples:
    ```python
    >>> import pyochain as pc
    >>> pc.Ok(7).iter().next()
    Some(7)
    >>> pc.Err("nothing!").iter().next()
    NONE

    ```
    """
    return self.ok().iter()

map

map(
    fn: Callable[Concatenate[T, P], R], *args: P.args, **kwargs: P.kwargs
) -> Result[R, E]

Maps a Result[T, E] to Result[U, E].

Done by applying a function to a contained Ok value, leaving an Err value untouched.

Parameters:

Name Type Description Default
fn Callable[Concatenate[T, P], R]

The function to apply to the Ok value.

required
*args P.args

Additional positional arguments to pass to fn.

()
**kwargs P.kwargs

Additional keyword arguments to pass to fn.

{}

Returns:

Type Description
Result[R, E]

Result[R, E]: A new Result with the mapped value if Ok, otherwise the original Err.

Example:

>>> import pyochain as pc
>>> pc.Ok(2).map(lambda x: x * 2)
Ok(4)
>>> pc.Err("error").map(lambda x: x * 2)
Err('error')

Source code in src/pyochain/_results/_result.py
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
def map[**P, R](
    self, fn: Callable[Concatenate[T, P], R], *args: P.args, **kwargs: P.kwargs
) -> Result[R, E]:
    """Maps a `Result[T, E]` to `Result[U, E]`.

    Done by applying a function to a contained `Ok` value,
    leaving an `Err` value untouched.

    Args:
        fn (Callable[Concatenate[T, P], R]): The function to apply to the `Ok` value.
        *args (P.args): Additional positional arguments to pass to fn.
        **kwargs (P.kwargs): Additional keyword arguments to pass to fn.

    Returns:
        Result[R, E]: A new `Result` with the mapped value if `Ok`, otherwise the original `Err`.

    Example:
    ```python
    >>> import pyochain as pc
    >>> pc.Ok(2).map(lambda x: x * 2)
    Ok(4)
    >>> pc.Err("error").map(lambda x: x * 2)
    Err('error')

    ```
    """
    return (
        Ok(fn(self.unwrap(), *args, **kwargs))
        if self.is_ok()
        else cast(Result[R, E], self)
    )

map_err

map_err(
    fn: Callable[Concatenate[E, P], R], *args: P.args, **kwargs: P.kwargs
) -> Result[T, R]

Maps a Result[T, E] to Result[T, R].

Done by applying a function to a contained Err value, leaving an Ok value untouched.

Parameters:

Name Type Description Default
fn Callable[Concatenate[E, P], R]

The function to apply to the Err value.

required
*args P.args

Additional positional arguments to pass to fn.

()
**kwargs P.kwargs

Additional keyword arguments to pass to fn.

{}

Returns:

Type Description
Result[T, R]

Result[T, R]: A new Result with the mapped error if Err, otherwise the original Ok.

Example:

>>> import pyochain as pc
>>> pc.Ok(2).map_err(len)
Ok(2)
>>> pc.Err("foo").map_err(len)
Err(3)

Source code in src/pyochain/_results/_result.py
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
def map_err[**P, R](
    self, fn: Callable[Concatenate[E, P], R], *args: P.args, **kwargs: P.kwargs
) -> Result[T, R]:
    """Maps a `Result[T, E]` to `Result[T, R]`.

    Done by applying a function to a contained `Err` value,
    leaving an `Ok` value untouched.

    Args:
        fn (Callable[Concatenate[E, P], R]): The function to apply to the `Err` value.
        *args (P.args): Additional positional arguments to pass to fn.
        **kwargs (P.kwargs): Additional keyword arguments to pass to fn.


    Returns:
        Result[T, R]: A new `Result` with the mapped error if `Err`, otherwise the original `Ok`.

    Example:
    ```python
    >>> import pyochain as pc
    >>> pc.Ok(2).map_err(len)
    Ok(2)
    >>> pc.Err("foo").map_err(len)
    Err(3)

    ```
    """
    return (
        Err(fn(self.unwrap_err(), *args, **kwargs))
        if self.is_err()
        else cast(Result[T, R], self)
    )

map_or

map_or(
    default: R, f: Callable[Concatenate[T, P], R], *args: P.args, **kwargs: P.kwargs
) -> R

Applies a function to the Ok value if present, otherwise returns the default value.

Parameters:

Name Type Description Default
default R

Value to return if the result is Err.

required
f Callable[Concatenate[T, P], R]

Function to apply to the Ok value.

required
*args P.args

Additional positional arguments to pass to f.

()
**kwargs P.kwargs

Additional keyword arguments to pass to f.

{}

Returns:

Name Type Description
R R

Result of f(value) if Ok, otherwise default.

Example:

>>> import pyochain as pc
>>> pc.Ok(2).map_or(10, lambda x: x * 2)
4
>>> pc.Err("err").map_or(10, lambda x: x * 2)
10

Source code in src/pyochain/_results/_result.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
def map_or[**P, R](
    self,
    default: R,
    f: Callable[Concatenate[T, P], R],
    *args: P.args,
    **kwargs: P.kwargs,
) -> R:
    """Applies a function to the `Ok` value if present, otherwise returns the default value.

    Args:
        default (R): Value to return if the result is Err.
        f (Callable[Concatenate[T, P], R]): Function to apply to the `Ok` value.
        *args (P.args): Additional positional arguments to pass to f.
        **kwargs (P.kwargs): Additional keyword arguments to pass to f.

    Returns:
        R: Result of f(value) if Ok, otherwise default.

    Example:
    ```python
    >>> import pyochain as pc
    >>> pc.Ok(2).map_or(10, lambda x: x * 2)
    4
    >>> pc.Err("err").map_or(10, lambda x: x * 2)
    10

    ```
    """
    return f(self.unwrap(), *args, **kwargs) if self.is_ok() else default

map_or_else

map_or_else(ok: Callable[[T], U], err: Callable[[E], U]) -> U

Maps a Result[T, E] to U.

Done by applying a fallback function to a contained Err value, or a default function to a contained Ok value.

Parameters:

Name Type Description Default
ok Callable[[T], U]

The function to apply to the Ok value.

required
err Callable[[E], U]

The function to apply to the Err value.

required

Returns:

Name Type Description
U U

The result of applying the appropriate function.

Example:

>>> import pyochain as pc
>>> k = 21
>>> pc.Ok("foo").map_or_else(len, lambda e: k * 2)
3
>>> pc.Err("bar").map_or_else(len, lambda e: k * 2)
42

Source code in src/pyochain/_results/_result.py
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
def map_or_else[U](self, ok: Callable[[T], U], err: Callable[[E], U]) -> U:
    """Maps a `Result[T, E]` to `U`.

    Done by applying a fallback function to a contained `Err` value,
    or a default function to a contained `Ok` value.

    Args:
        ok (Callable[[T], U]): The function to apply to the `Ok` value.
        err (Callable[[E], U]): The function to apply to the `Err` value.

    Returns:
        U: The result of applying the appropriate function.

    Example:
    ```python
    >>> import pyochain as pc
    >>> k = 21
    >>> pc.Ok("foo").map_or_else(len, lambda e: k * 2)
    3
    >>> pc.Err("bar").map_or_else(len, lambda e: k * 2)
    42

    ```
    """
    return ok(self.unwrap()) if self.is_ok() else err(self.unwrap_err())

ok

ok() -> Option[T]

Converts from Result[T, E] to Option[T].

Ok(v) becomes Some(v), and Err(e) becomes None.

Returns:

Type Description
Option[T]

Option[T]: An Option containing the Ok value, or None if the result is Err.

Example:

>>> import pyochain as pc
>>> pc.Ok(2).ok()
Some(2)
>>> pc.Err("error").ok()
NONE

Source code in src/pyochain/_results/_result.py
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
def ok(self) -> Option[T]:
    """Converts from `Result[T, E]` to `Option[T]`.

    `Ok(v)` becomes `Some(v)`, and `Err(e)` becomes `None`.

    Returns:
        Option[T]: An `Option` containing the `Ok` value, or `None` if the result is `Err`.

    Example:
    ```python
    >>> import pyochain as pc
    >>> pc.Ok(2).ok()
    Some(2)
    >>> pc.Err("error").ok()
    NONE

    ```
    """
    from ._option import NONE, Some

    return Some(self.unwrap()) if self.is_ok() else NONE

or_

or_(res: Result[T, F]) -> Result[T, F]

Returns res if the result is Err, otherwise returns the Ok value of self.

Parameters:

Name Type Description Default
res Result[T, F]

The result to return if the original result is Err.

required

Returns:

Type Description
Result[T, F]

Result[T, F]: The original Ok value, or res if the original result is Err.

Examples:

>>> import pyochain as pc
>>> pc.Ok(2).or_(pc.Err("late error"))
Ok(2)
>>> pc.Err("early error").or_(pc.Ok(2))
Ok(2)
>>> pc.Err("not a 2").or_(pc.Err("late error"))
Err('late error')
>>> pc.Ok(2).or_(pc.Ok(100))
Ok(2)

Source code in src/pyochain/_results/_result.py
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
def or_[F](self, res: Result[T, F]) -> Result[T, F]:
    """Returns res if the result is `Err`, otherwise returns the `Ok` value of **self**.

    Args:
        res (Result[T, F]): The result to return if the original result is `Err`.

    Returns:
        Result[T, F]: The original `Ok` value, or `res` if the original result is `Err`.

    Examples:
    ```python
    >>> import pyochain as pc
    >>> pc.Ok(2).or_(pc.Err("late error"))
    Ok(2)
    >>> pc.Err("early error").or_(pc.Ok(2))
    Ok(2)
    >>> pc.Err("not a 2").or_(pc.Err("late error"))
    Err('late error')
    >>> pc.Ok(2).or_(pc.Ok(100))
    Ok(2)

    ```
    """
    return cast(Result[T, F], self) if self.is_ok() else res

or_else

or_else(
    fn: Callable[Concatenate[E, P], Result[T, E]], *args: P.args, **kwargs: P.kwargs
) -> Result[T, E]

Calls a function if the result is Err, otherwise returns the Ok value.

This is often used for handling errors by trying an alternative operation.

Parameters:

Name Type Description Default
fn Callable[Concatenate[E, P], Result[T, E]]

The function to call with the Err value.

required
*args P.args

Additional positional arguments to pass to fn.

()
**kwargs P.kwargs

Additional keyword arguments to pass to fn.

{}

Returns:

Type Description
Result[T, E]

Result[T, E]: The original Ok value, or the result of the function if Err.

Example:

>>> import pyochain as pc
>>> def fallback(e: str) -> Result[int, str]:
...     return pc.Ok(len(e))
>>> pc.Ok(2).or_else(fallback)
Ok(2)
>>> pc.Err("foo").or_else(fallback)
Ok(3)

Source code in src/pyochain/_results/_result.py
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
516
517
def or_else[**P](
    self,
    fn: Callable[Concatenate[E, P], Result[T, E]],
    *args: P.args,
    **kwargs: P.kwargs,
) -> Result[T, E]:
    """Calls a function if the result is `Err`, otherwise returns the `Ok` value.

    This is often used for handling errors by trying an alternative operation.

    Args:
        fn (Callable[Concatenate[E, P], Result[T, E]]): The function to call with the `Err` value.
        *args (P.args): Additional positional arguments to pass to fn.
        **kwargs (P.kwargs): Additional keyword arguments to pass to fn.

    Returns:
        Result[T, E]: The original `Ok` value, or the result of the function if `Err`.

    Example:
    ```python
    >>> import pyochain as pc
    >>> def fallback(e: str) -> Result[int, str]:
    ...     return pc.Ok(len(e))
    >>> pc.Ok(2).or_else(fallback)
    Ok(2)
    >>> pc.Err("foo").or_else(fallback)
    Ok(3)

    ```
    """
    return self if self.is_ok() else fn(self.unwrap_err(), *args, **kwargs)

tap

tap(
    func: Callable[Concatenate[Self, P], Any], *args: P.args, **kwargs: P.kwargs
) -> Self

Tap into the chain to perform side effects without altering the data.

Parameters:

Name Type Description Default
func Callable[Concatenate[Self, P], Any]

Function to apply to the instance for side effects.

required
*args P.args

Positional arguments to pass to the function.

()
**kwargs P.kwargs

Keyword arguments to pass to the function.

{}

Returns:

Name Type Description
Self Self

The instance itself for chaining.

Example:

>>> import pyochain as pc
>>> pc.Seq([1, 2, 3, 4]).tap(print).last()
Seq(1, 2, 3, 4)
4

Source code in src/pyochain/_core/_main.py
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
def tap[**P](
    self,
    func: Callable[Concatenate[Self, P], Any],
    *args: P.args,
    **kwargs: P.kwargs,
) -> Self:
    """Tap into the chain to perform side effects without altering the data.

    Args:
        func (Callable[Concatenate[Self, P], Any]): Function to apply to the instance for side effects.
        *args (P.args): Positional arguments to pass to the function.
        **kwargs (P.kwargs): Keyword arguments to pass to the function.

    Returns:
        Self: The instance itself for chaining.

    Example:
    ```python
    >>> import pyochain as pc
    >>> pc.Seq([1, 2, 3, 4]).tap(print).last()
    Seq(1, 2, 3, 4)
    4

    ```
    """
    func(self, *args, **kwargs)
    return self

transpose

transpose() -> Option[Result[T, E]]

Transposes a Result containing an Option into an Option containing a Result.

Can only be called if the inner type is Option[T, E].

Ok(Some(v)) -> Some(Ok(v)), Ok(NONE) -> NONE, Err(e) -> Some(Err(e))

Returns:

Type Description
Option[Result[T, E]]

Option[Result[T, E]]: Option containing a Result or NONE.

Example:

>>> import pyochain as pc
>>> pc.Ok(pc.Some(2)).transpose()
Some(Ok(2))
>>> pc.Ok(pc.NONE).transpose()
NONE
>>> pc.Err("err").transpose()
Some(Err('err'))

Source code in src/pyochain/_results/_result.py
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
def transpose(self: Result[Option[T], E]) -> Option[Result[T, E]]:
    """Transposes a Result containing an Option into an Option containing a Result.

    Can only be called if the inner type is `Option[T, E]`.

    `Ok(Some(v)) -> Some(Ok(v)), Ok(NONE) -> NONE, Err(e) -> Some(Err(e))`

    Returns:
        Option[Result[T, E]]: Option containing a Result or NONE.

    Example:
    ```python
    >>> import pyochain as pc
    >>> pc.Ok(pc.Some(2)).transpose()
    Some(Ok(2))
    >>> pc.Ok(pc.NONE).transpose()
    NONE
    >>> pc.Err("err").transpose()
    Some(Err('err'))

    ```
    """
    from ._option import NONE, Option, Some

    r = Option[Result[T, E]]

    if self.is_err():
        return cast(r, Some(Err(self.unwrap_err())))
    opt = self.unwrap()
    if opt.is_none():
        return NONE
    return cast(r, Some(Ok(opt.unwrap())))

unwrap

unwrap() -> Never
Source code in src/pyochain/_results/_result.py
772
773
774
def unwrap(self) -> Never:
    msg = f"called `unwrap` on Err: {self.error!r}"
    raise ResultUnwrapError(msg)

unwrap_err

unwrap_err() -> E
Source code in src/pyochain/_results/_result.py
776
777
def unwrap_err(self) -> E:
    return self.error

unwrap_or

unwrap_or(default: T) -> T

Returns the contained Ok value or a provided default.

Parameters:

Name Type Description Default
default T

The value to return if the result is Err.

required

Returns:

Name Type Description
T T

The contained Ok value or the provided default.

Example:

>>> import pyochain as pc
>>> pc.Ok(2).unwrap_or(10)
2
>>> pc.Err("error").unwrap_or(10)
10

Source code in src/pyochain/_results/_result.py
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
def unwrap_or(self, default: T) -> T:
    """Returns the contained `Ok` value or a provided default.

    Args:
        default (T): The value to return if the result is `Err`.

    Returns:
        T: The contained `Ok` value or the provided default.

    Example:
    ```python
    >>> import pyochain as pc
    >>> pc.Ok(2).unwrap_or(10)
    2
    >>> pc.Err("error").unwrap_or(10)
    10

    ```
    """
    return self.unwrap() if self.is_ok() else default

unwrap_or_else

unwrap_or_else(
    fn: Callable[Concatenate[E, P], T], *args: P.args, **kwargs: P.kwargs
) -> T

Returns the contained Ok value or computes it from a function.

Parameters:

Name Type Description Default
fn Callable[Concatenate[E, P], T]

A function that takes the Err value and returns a default value.

required
*args P.args

Additional positional arguments to pass to fn.

()
**kwargs P.kwargs

Additional keyword arguments to pass to fn.

{}

Returns:

Name Type Description
T T

The contained Ok value or the result of the function.

Example:

>>> import pyochain as pc
>>> pc.Ok(2).unwrap_or_else(len)
2
>>> pc.Err("foo").unwrap_or_else(len)
3

Source code in src/pyochain/_results/_result.py
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
def unwrap_or_else[**P](
    self, fn: Callable[Concatenate[E, P], T], *args: P.args, **kwargs: P.kwargs
) -> T:
    """Returns the contained `Ok` value or computes it from a function.

    Args:
        fn (Callable[Concatenate[E, P], T]): A function that takes the `Err` value and returns a default value.
        *args (P.args): Additional positional arguments to pass to fn.
        **kwargs (P.kwargs): Additional keyword arguments to pass to fn.

    Returns:
        T: The contained `Ok` value or the result of the function.

    Example:
    ```python
    >>> import pyochain as pc
    >>> pc.Ok(2).unwrap_or_else(len)
    2
    >>> pc.Err("foo").unwrap_or_else(len)
    3

    ```
    """
    return self.unwrap() if self.is_ok() else fn(self.unwrap_err(), *args, **kwargs)