Skip to content

ResultType

Bases: Pipe, Protocol


              flowchart TD
              pyochain.core._result.ResultType[ResultType]
              pyochain.abc._mixins.Pipe[Pipe]

                              pyochain.abc._mixins.Pipe --> pyochain.core._result.ResultType
                


              click pyochain.core._result.ResultType href "" "pyochain.core._result.ResultType"
              click pyochain.abc._mixins.Pipe href "" "pyochain.abc._mixins.Pipe"
            

This is the base Protocol defined for returning and propagating errors.

Result[T, E] is a the type union of the two possibles variants of the Protocol:

  • Ok[T, E], representing success and containing a value
  • Err[T, E], representing error and containing an error value

Functions return Result whenever errors are expected and recoverable.

For example, I/O or web requests can fail for many reasons, and using Result forces the caller to handle the possibility of failure.

This is directly inspired by Rust's Result type, and provides similar functionality for error handling in Python.

Note

Due to Python typing nature, we need to separate both the Protocol definition (ResultType), and the type union (Result), which is the public facing type that users will interact with.

This separation allows type checkers to flag exhaustive handling of both variants, in match statements notably, while avoiding duplicated docstrings and method definitions.

Warning

Do not try to instanciate this class, as it don't exist at runtime.

Result does in fact exist in the namespace, but it's an empty Rust struct,

and your type checker will warn you in any case because a type Result = ... is not supposed to be instanciable.

Example
from pyochain import Err, Ok, Result

def is_positive(x: int) -> Result[str, ValueError]:
    if x > 0:
        return Ok(f"Value is {x}")
    msg = f"{x} is not positive"
    return Err(ValueError(msg))

def handle_variant(x: Result[str, ValueError]) -> str:
    match x:
        case Ok(value):
            return f"Success: {value}"
        case Err(error):
            return f"Failure: {error}"

res1 = is_positive(5).map(lambda s: s.upper()).pipe(handle_variant)
assert res1 == "Success: VALUE IS 5"

res2 = is_positive(-3).map(lambda s: s.upper()).pipe(handle_variant)
assert res2 == "Failure: -3 is not positive"
Source code in pyochain/core/_result.pyi
 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
313
314
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
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
589
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
616
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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
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
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
@type_check_only
class ResultType[T, E](Pipe, Protocol):
    """This is the base Protocol defined for returning and propagating errors.

    `Result[T, E]` is a the type union of the two possibles variants of the Protocol:

    - `Ok[T, E]`, representing success and containing a value
    - `Err[T, E]`, representing error and containing an error value

    Functions return `Result` whenever errors are expected and recoverable.

    For example, I/O or web requests can fail for many reasons, and using `Result` forces the caller to handle the possibility of failure.

    This is directly inspired by Rust's `Result` type, and provides similar functionality for error handling in Python.

    Note:
        Due to Python typing nature, we need to separate both the Protocol definition (`ResultType`), and the type union (`Result`), which is the public facing type that users will interact with.

        This separation allows type checkers to flag exhaustive handling of both variants, in `match` statements notably, while avoiding duplicated docstrings and method definitions.

    Warning:
        Do not try to instanciate this class, as it don't exist at runtime.

        `Result` does in fact exist in the namespace, but it's an empty `Rust` struct,

        and your type checker will warn you in any case because a `type Result = ...` is not supposed to be instanciable.

    Example:
        ```python
        from pyochain import Err, Ok, Result

        def is_positive(x: int) -> Result[str, ValueError]:
            if x > 0:
                return Ok(f"Value is {x}")
            msg = f"{x} is not positive"
            return Err(ValueError(msg))

        def handle_variant(x: Result[str, ValueError]) -> str:
            match x:
                case Ok(value):
                    return f"Success: {value}"
                case Err(error):
                    return f"Failure: {error}"

        res1 = is_positive(5).map(lambda s: s.upper()).pipe(handle_variant)
        assert res1 == "Success: VALUE IS 5"

        res2 = is_positive(-3).map(lambda s: s.upper()).pipe(handle_variant)
        assert res2 == "Failure: -3 is not positive"
        ```
    """
    @override
    def __eq__(self, other: object) -> bool:
        """Checks equality between two `Result` instances.

        Args:
            other (object): The other object to compare with.

        Returns:
            bool: `True` if both are the same variant and their contained values are equal, `False` otherwise.

        Example:
            ```python
            from pyochain import Ok, Err

            assert Ok(2) == Ok(2)
            assert Err("error") == Err("error")
            ```
        """
    @override
    def __ne__(self, value: object, /) -> bool:
        """Checks inequality between two `Result` instances.

        Args:
            value (object): The other object to compare with.

        Returns:
            bool: `True` if both are not the same variant or their contained values are not equal, `False` otherwise.

        Example:
            ```python
            from pyochain import Ok, Err

            assert Ok(2) != Err("error")
            assert Err("error") != Ok(2)
            assert Ok(2) != 2
            assert Err("error") != "error"
            ```
        """
    def swap(self) -> Result[E, T]:
        """Swaps the `Ok` and `Err` variants.

        Converts an `Ok[T]` into an `Err[T]` and an `Err[E]` into an `Ok[E]`.

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

        Example:
            ```python
            from pyochain import Ok, Err

            assert Ok(2).swap().unwrap_err() == 2
            assert Err("error").swap().unwrap() == "error"
            ```
        """
    def flatten[T1, E1](self: Result[Result[T1, E1], E1]) -> Result[T1, E1]:
        """Flattens a nested `Result`.

        Converts from `Result[Result[T1, E1], E1]` to `Result[T1, E1]`.

        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[T1, E1]: The flattened result.

        Example:
            ```python
            from pyochain import Ok, Err, Result

            a: Result[Result[str, int], int] = Ok(Ok("hello"))
            assert Ok("hello") == a.flatten()
            b: Result[Result[str, int], int] = Ok(Err(6))
            assert Err(6) == b.flatten()
            c: Result[Result[str, int], int] = Err(6)
            assert Err(6) == c.flatten()
            # flattening only remove one level of nesting at a time
            d: Result[Result[Result[str, int], int], int] = Ok(Ok(Ok("hello")))
            assert Ok(Ok("hello")) == d.flatten()
            assert Ok("hello") == d.flatten().flatten()
            ```
        """

    def iter(self) -> PyoIterator[T]:
        """Returns an `Iterator` over the possibly contained value.

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

        Example:
            ```python
            from pyochain import Ok, Err, Some

            assert Ok(7).iter().next() == Some(7)
            assert Err("nothing!").iter().next().is_none()
            ```
        """

    @overload
    def map_star[R](
        self: Result[tuple[Any], E],
        func: Callable[[Any], R],
    ) -> Result[R, E]: ...
    @overload
    def map_star[T1, T2, R](
        self: Result[tuple[T1, T2], E],
        func: Callable[[T1, T2], R],
    ) -> Result[R, E]: ...
    @overload
    def map_star[T1, T2, T3, R](
        self: Result[tuple[T1, T2, T3], E],
        func: Callable[[T1, T2, T3], R],
    ) -> Result[R, E]: ...
    @overload
    def map_star[T1, T2, T3, T4, R](
        self: Result[tuple[T1, T2, T3, T4], E],
        func: Callable[[T1, T2, T3, T4], R],
    ) -> Result[R, E]: ...
    @overload
    def map_star[T1, T2, T3, T4, T5, R](
        self: Result[tuple[T1, T2, T3, T4, T5], E],
        func: Callable[[T1, T2, T3, T4, T5], R],
    ) -> Result[R, E]: ...
    @overload
    def map_star[T1, T2, T3, T4, T5, T6, R](
        self: Result[tuple[T1, T2, T3, T4, T5, T6], E],
        func: Callable[[T1, T2, T3, T4, T5, T6], R],
    ) -> Result[R, E]: ...
    @overload
    def map_star[T1, T2, T3, T4, T5, T6, T7, R](
        self: Result[tuple[T1, T2, T3, T4, T5, T6, T7], E],
        func: Callable[[T1, T2, T3, T4, T5, T6, T7], R],
    ) -> Result[R, E]: ...
    @overload
    def map_star[T1, T2, T3, T4, T5, T6, T7, T8, R](
        self: Result[tuple[T1, T2, T3, T4, T5, T6, T7, T8], E],
        func: Callable[[T1, T2, T3, T4, T5, T6, T7, T8], R],
    ) -> Result[R, E]: ...
    @overload
    def map_star[T1, T2, T3, T4, T5, T6, T7, T8, T9, R](
        self: Result[tuple[T1, T2, T3, T4, T5, T6, T7, T8, T9], E],
        func: Callable[[T1, T2, T3, T4, T5, T6, T7, T8, T9], R],
    ) -> Result[R, E]: ...
    @overload
    def map_star[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, R](
        self: Result[tuple[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10], E],
        func: Callable[[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10], R],
    ) -> Result[R, E]: ...
    def map_star[U: tuple[Any, ...], R](
        self: ResultType[U, E],
        func: Callable[..., R],
    ) -> Result[R, E]:
        """Maps a `Result[tuple, E]` to `Result[R, E]` by unpacking the tuple.

        Done by applying a function to a contained `Ok` value (which is expected to be a `tuple`).

        Args:
            func (Callable[..., R]): The function to apply to the unpacked `Ok` value.

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

        Example:
            ```python
            from pyochain import Ok, Err
            from operator import add

            assert Ok((2, 3)).map_star(add).unwrap() == 5
            assert Err("error").map_star(add).unwrap_err() == "error"
            ```
        """

    @overload
    def and_then_star[S, T1, R](
        self: Result[tuple[T1], S],
        func: Callable[[T1], Result[R, S]],
    ) -> Result[R, S]: ...
    @overload
    def and_then_star[S, T1, T2, R](
        self: Result[tuple[T1, T2], S],
        func: Callable[[T1, T2], Result[R, S]],
    ) -> Result[R, S]: ...
    @overload
    def and_then_star[S, T1, T2, T3, R](
        self: Result[tuple[T1, T2, T3], S],
        func: Callable[[T1, T2, T3], Result[R, S]],
    ) -> Result[R, S]: ...
    @overload
    def and_then_star[S, T1, T2, T3, T4, R](
        self: Result[tuple[T1, T2, T3, T4], S],
        func: Callable[[T1, T2, T3, T4], Result[R, S]],
    ) -> Result[R, S]: ...
    @overload
    def and_then_star[S, T1, T2, T3, T4, T5, R](
        self: Result[tuple[T1, T2, T3, T4, T5], S],
        func: Callable[[T1, T2, T3, T4, T5], Result[R, S]],
    ) -> Result[R, S]: ...
    @overload
    def and_then_star[S, T1, T2, T3, T4, T5, T6, R](
        self: Result[tuple[T1, T2, T3, T4, T5, T6], S],
        func: Callable[[T1, T2, T3, T4, T5, T6], Result[R, S]],
    ) -> Result[R, S]: ...
    @overload
    def and_then_star[S, T1, T2, T3, T4, T5, T6, T7, R](
        self: Result[tuple[T1, T2, T3, T4, T5, T6, T7], S],
        func: Callable[[T1, T2, T3, T4, T5, T6, T7], Result[R, S]],
    ) -> Result[R, S]: ...
    @overload
    def and_then_star[S, T1, T2, T3, T4, T5, T6, T7, T8, R](
        self: Result[tuple[T1, T2, T3, T4, T5, T6, T7, T8], S],
        func: Callable[[T1, T2, T3, T4, T5, T6, T7, T8], Result[R, S]],
    ) -> Result[R, S]: ...
    @overload
    def and_then_star[S, T1, T2, T3, T4, T5, T6, T7, T8, T9, R](
        self: Result[tuple[T1, T2, T3, T4, T5, T6, T7, T8, T9], S],
        func: Callable[[T1, T2, T3, T4, T5, T6, T7, T8, T9], Result[R, S]],
    ) -> Result[R, S]: ...
    @overload
    def and_then_star[S, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, R](
        self: Result[tuple[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10], S],
        func: Callable[[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10], Result[R, S]],
    ) -> Result[R, S]: ...
    def and_then_star[U: tuple[Any, ...], R](
        self: Result[U, E], func: Callable[..., Result[R, E]]
    ) -> Result[R, E]:
        """Calls a function if the result is `Ok`, unpacking the tuple.

        Done by applying a function to a contained `Ok` value (which is expected to be a tuple).

        Args:
            func (Callable[..., Result[R, E]]): The function to call with the unpacked `Ok` value.

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

        Example:
            ```python
            from pyochain import Ok, Err, Result

            def to_str(x: int, y: int) -> Result[str, str]:
                return Ok(f"{x},{y}")

            assert Ok((2, 3)).and_then_star(to_str).unwrap() == "2,3"
            assert Err("error").and_then_star(to_str).unwrap_err() == "error"
            ```
        """

    def is_ok(self) -> bool:
        """Returns `True` if the result is `Ok`.

        Returns:
            bool: `True` if the result is an `Ok` variant, `False` otherwise.

        Example:
            ```python
            from pyochain import Ok, Err, Result

            x: Result[int, str] = Ok(2)
            assert x.is_ok()

            y: Result[int, str] = Err("Some error message")
            assert not y.is_ok()
            ```
        """

    def is_err(self) -> bool:
        """Returns `True` if the result is `Err`.

        Returns:
            bool: `True` if the result is an `Err` variant, `False` otherwise.

        Example:
            ```python
            from pyochain import Ok, Err, Result

            x: Result[int, str] = Ok(2)
            assert not x.is_err()

            y: Result[int, str] = Err("Some error message")
            assert y.is_err()
            ```
        """

    def unwrap(self) -> T:
        """Returns the contained `Ok` value.

        raises `ResultUnwrapError` if the result is `Err`.

        Returns:
            T: The contained `Ok` value.

        Example:
            ```python
            from pyochain import Ok, Err, ResultUnwrapError

            assert Ok(2).unwrap() == 2

            try:
                _ = Err(1).unwrap()
            except ResultUnwrapError as e:
                assert str(e) == "called `unwrap` on an `Err`: 1"
            ```
        """

    def unwrap_err(self) -> E:
        """Returns the contained `Err` value.

        raises `ResultUnwrapError` if the result is `Ok`.

        Returns:
            E: The contained `Err` value.

        Example:
            ```python
            from pyochain import Err

            assert Err("emergency failure").unwrap_err() == "emergency failure"
            ```
            ```python
            from pyochain import Ok, ResultUnwrapError

            try:
                _ = Ok(2).unwrap_err()
            except ResultUnwrapError as e:
                assert str(e) == "called `unwrap_err` on Ok"
            ```
        """

    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
            from pyochain import Ok, Err

            k = 21
            assert Ok("foo").map_or_else(len, lambda e: k * 2) == 3
            assert Err("bar").map_or_else(len, lambda e: k * 2) == 42
            ```
        """

    def expect(self, msg: str) -> T:
        """Returns the contained `Ok` value.

        raises `ResultUnwrapError` 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.

        Example:
            ```python
            from pyochain import Err, Ok, ResultUnwrapError

            assert Ok(2).expect("No error") == 2
            try:
                _ = Err(1).expect("Unexpected error")
            except ResultUnwrapError as e:
                assert str(e) == "Unexpected error: 1"
            ```
        """

    def expect_err(self, msg: str) -> E:
        """Returns the contained `Err` value.

        raises `ResultUnwrapError` 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.

        Example:
            ```python
            from pyochain import Err, Ok, ResultUnwrapError

            e = Err("emergency failure").expect_err("Testing expect_err")
            assert str(e) == "emergency failure"
            try:
                _ = Ok(10).expect_err("Testing expect_err")
            except ResultUnwrapError as e:
                assert str(e) == "Testing expect_err: expected Err, got Ok(10)"
            ```
        """

    def unwrap_or[D](self, default: D) -> T | D:
        """Returns the contained `Ok` value or a provided default.

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

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

        Example:
            ```python
            from pyochain import Ok, Err

            assert Ok(2).unwrap_or(10) == 2
            assert Err("error").unwrap_or(10) == 10
            ```
        """

    def unwrap_or_else[**P, O](
        self, fn: Callable[Concatenate[E, P], O], *args: P.args, **kwargs: P.kwargs
    ) -> T | O:
        """Returns the contained `Ok` value or computes it from a function.

        Args:
            fn (Callable[Concatenate[E, P], O]): 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 | O: The contained `Ok` value or the result of the function.

        Example:
            ```python
            from pyochain import Ok, Err

            assert Ok(2).unwrap_or_else(len) == 2
            assert Err("foo").unwrap_or_else(len) == 3
            ```
        """

    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
            from pyochain import Ok, Err

            assert Ok(2).map(lambda x: x * 2).unwrap() == 4
            assert Err("error").map(lambda x: x * 2).unwrap_err() == "error"
            ```
        """

    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
            from pyochain import Ok, Err

            assert Ok(2).map_err(len).unwrap() == 2
            assert Err("foo").map_err(len).unwrap_err() == 3
            ```
        """
    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
            from pyochain import Ok, Vec

            seen = Vec[int](())
            assert Ok(2).inspect(lambda x: seen.append(x)).unwrap() == 2
            assert seen == Vec(2)
            ```
        """

    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
            from pyochain import Err, Vec

            seen = Vec[str](())
            res = Err("oops").inspect_err(lambda e: seen.append(e)).unwrap_err()
            assert res == "oops"
            assert seen == Vec(["oops"])
            ```
        """

    def and_[O, U](self, res: Result[U, O]) -> Result[U, E | O]:
        """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, O]): The result to return if the original result is `Ok`.

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

        Example:
            ```python
            from pyochain import Ok, Err

            x = Ok(2)
            y = Err("late error")
            assert x.and_(y).unwrap_err() == "late error"

            x = Err("early error")
            y = Ok("foo")
            assert x.and_(y).unwrap_err() == "early error"

            x = Err("not a 2")
            y = Err("late error")
            assert x.and_(y).unwrap_err() == "not a 2"

            x = Ok(2)
            y = Ok("different result type")
            assert x.and_(y).unwrap() == "different result type"
            ```
        """

    @overload
    def and_then[T1, E1](
        self: Result[T1, E1], fn: type[ResultType[Any, Any]]
    ) -> Result[T1, E1]: ...
    @overload
    def and_then[**P, T1, E1, R](
        self: Result[T1, E1],
        fn: Callable[Concatenate[T1, P], Result[R, E1]],
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> Result[R, E1]: ...
    def and_then[**P, T1, E1, R](
        self: Result[T1, E1],
        fn: Callable[Concatenate[T1, P], Result[R, E1]] | type[ResultType[Any, Any]],
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> Result[R, E1]:
        """Calls `fn` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.

        This function can be used for control flow based on `Result` values.

        Args:
            fn (Callable[Concatenate[T1, P], Result[R, E1]] | type[ResultType[Any, Any]]): 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, E1]: The result of calling `fn` if the original result is `Ok`, otherwise the original `Err`.

        Examples:
            ```python
            from pyochain import Ok, Err, Result

            def try_mul_to_str(x: int) -> Result[str, str]:
                if x < 100_000:
                    return Ok(str(x * x))
                else:
                    return Err("overflow")

            assert Ok(2).and_then(try_mul_to_str) == Ok("4")
            assert Ok(1_000_000).and_then(try_mul_to_str) == Err("overflow")
            assert Err("hi").and_then(try_mul_to_str) == Err("hi")
            ```

            Often used to chain fallible operations that may return [`Err`].

            ```python
            from pyochain import Option, Some, NONE
            from pathlib import Path

            CONFIG = Path("pyproject")

            def run(value: int = 10, path: Option[str] = NONE) -> Result[float, str]:
                return (
                    check_toml(path.map(Path).unwrap_or(CONFIG))
                    .map(lambda _: value)
                    .and_then(parse_int)
                    .and_then(reciprocal)
                )

            def check_toml(path: Path) -> Result[None, str]:
                p = path.with_suffix(".toml")
                if p.exists():
                    return Ok(None)
                else:
                    return Err(f"File {p} does not exist")

            def parse_int(s: str) -> Result[int, str]:
                try:
                    return Ok(int(s))
                except ValueError:
                    return Err(f"'{s}' is not a valid int")

            def reciprocal(x: int) -> Result[float, str]:
                if x == 0:
                    return Err("division by zero")
                else:
                    return Ok(1 / x)

            assert run() == Ok(0.1)
            assert run(path=Some("ruff")) == Ok(0.1)
            assert run(path=Some("bad")) == Err("File bad.toml does not exist")
            assert run(value=0) == Err("division by zero")
            assert run(value="hi") == Err("'hi' is not a valid int")
            ```
        """

    def or_else[**P, R](
        self,
        fn: Callable[Concatenate[E, P], Result[object, R]],
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> Result[T, R]:
        """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[object, R]]): 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, R]: The original `Ok` value, or the result of the function if `Err`.

        Example:
            ```python
            from pyochain import Ok, Err, Result

            def fallback(e: str) -> Result[int, str]:
                return Ok(len(e))

            assert Ok(2).or_else(fallback).unwrap() == 2
            assert Err("foo").or_else(fallback).unwrap() == 3
            ```
        """

    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
                from pyochain import Ok, Err, Some

                assert Ok(2).ok().unwrap() == 2
                assert Err("error").ok().is_none()
                ```
        """

    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
            from pyochain import Ok, Err, Some

            assert Ok(2).err().is_none()
            assert Err("error").err().unwrap() == "error"
            ```
        """

    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
            from pyochain import Ok, Err

            assert Ok(2).is_ok_and(lambda x: x > 1)
            assert not Ok(0).is_ok_and(lambda x: x > 1)
            assert not Err("err").is_ok_and(lambda x: x > 1)
            ```
        """

    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
            from pyochain import Err, Ok

            assert Err("foo").is_err_and(lambda e: len(e) == 3)
            assert not Err("bar").is_err_and(lambda e: e == "baz")
            assert not Ok(2).is_err_and(lambda e: True)
            ```
        """

    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
            from pyochain import Ok, Err

            assert Ok(2).map_or(10, lambda x: x * 2) == 4
            assert Err("err").map_or(10, lambda x: x * 2) == 10
            ```
        """

    def transpose[S](self: ResultType[Option[S], E]) -> Option[Result[S, E]]:
        """Transposes a Result containing an Option into an Option containing a Result.

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

        The mapping is as follows:

        - `Ok(Some(v))` becomes `Some(Ok(v))`
        - `Ok(NONE)` becomes `NONE`
        - `Err(e)` becomes `Some(Err(e))`

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

        Example:
            ```python
            from pyochain import Ok, Err, Some, NONE

            assert Ok(Some(2)).transpose().unwrap().unwrap() == 2
            assert Ok(NONE).transpose().is_none()
            assert Err("err").transpose().unwrap().unwrap_err() == "err"
            ```
        """

    def or_[S, F](self, res: Result[S, F]) -> Result[T | S, F]:
        """Returns res if the result is `Err`, otherwise returns the `Ok` value of **self**.

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

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

        Example:
            ```python
            from pyochain import Ok, Err

            assert Ok(2).or_(Err("late error")).unwrap() == 2
            assert Err("early error").or_(Ok(2)).unwrap() == 2
            assert Err("not a 2").or_(Err("late error")).unwrap_err() == "late error"
            assert Ok(2).or_(Ok(100)).unwrap() == 2
            ```
        """

__eq__(other)

Checks equality between two Result instances.

Parameters:

Name Type Description Default
other object

The other object to compare with.

required

Returns:

Name Type Description
bool bool

True if both are the same variant and their contained values are equal, False otherwise.

Example
from pyochain import Ok, Err

assert Ok(2) == Ok(2)
assert Err("error") == Err("error")
Source code in pyochain/core/_result.pyi
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
@override
def __eq__(self, other: object) -> bool:
    """Checks equality between two `Result` instances.

    Args:
        other (object): The other object to compare with.

    Returns:
        bool: `True` if both are the same variant and their contained values are equal, `False` otherwise.

    Example:
        ```python
        from pyochain import Ok, Err

        assert Ok(2) == Ok(2)
        assert Err("error") == Err("error")
        ```
    """

__ne__(value)

Checks inequality between two Result instances.

Parameters:

Name Type Description Default
value object

The other object to compare with.

required

Returns:

Name Type Description
bool bool

True if both are not the same variant or their contained values are not equal, False otherwise.

Example
from pyochain import Ok, Err

assert Ok(2) != Err("error")
assert Err("error") != Ok(2)
assert Ok(2) != 2
assert Err("error") != "error"
Source code in pyochain/core/_result.pyi
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
@override
def __ne__(self, value: object, /) -> bool:
    """Checks inequality between two `Result` instances.

    Args:
        value (object): The other object to compare with.

    Returns:
        bool: `True` if both are not the same variant or their contained values are not equal, `False` otherwise.

    Example:
        ```python
        from pyochain import Ok, Err

        assert Ok(2) != Err("error")
        assert Err("error") != Ok(2)
        assert Ok(2) != 2
        assert Err("error") != "error"
        ```
    """

swap()

Swaps the Ok and Err variants.

Converts an Ok[T] into an Err[T] and an Err[E] into an Ok[E].

Returns:

Type Description
Result[E, T]

Result[E, T]: The swapped result.

Example
from pyochain import Ok, Err

assert Ok(2).swap().unwrap_err() == 2
assert Err("error").swap().unwrap() == "error"
Source code in pyochain/core/_result.pyi
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
def swap(self) -> Result[E, T]:
    """Swaps the `Ok` and `Err` variants.

    Converts an `Ok[T]` into an `Err[T]` and an `Err[E]` into an `Ok[E]`.

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

    Example:
        ```python
        from pyochain import Ok, Err

        assert Ok(2).swap().unwrap_err() == 2
        assert Err("error").swap().unwrap() == "error"
        ```
    """

flatten()

Flattens a nested Result.

Converts from Result[Result[T1, E1], E1] to Result[T1, E1].

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[T1, E1]

Result[T1, E1]: The flattened result.

Example
from pyochain import Ok, Err, Result

a: Result[Result[str, int], int] = Ok(Ok("hello"))
assert Ok("hello") == a.flatten()
b: Result[Result[str, int], int] = Ok(Err(6))
assert Err(6) == b.flatten()
c: Result[Result[str, int], int] = Err(6)
assert Err(6) == c.flatten()
# flattening only remove one level of nesting at a time
d: Result[Result[Result[str, int], int], int] = Ok(Ok(Ok("hello")))
assert Ok(Ok("hello")) == d.flatten()
assert Ok("hello") == d.flatten().flatten()
Source code in pyochain/core/_result.pyi
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
def flatten[T1, E1](self: Result[Result[T1, E1], E1]) -> Result[T1, E1]:
    """Flattens a nested `Result`.

    Converts from `Result[Result[T1, E1], E1]` to `Result[T1, E1]`.

    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[T1, E1]: The flattened result.

    Example:
        ```python
        from pyochain import Ok, Err, Result

        a: Result[Result[str, int], int] = Ok(Ok("hello"))
        assert Ok("hello") == a.flatten()
        b: Result[Result[str, int], int] = Ok(Err(6))
        assert Err(6) == b.flatten()
        c: Result[Result[str, int], int] = Err(6)
        assert Err(6) == c.flatten()
        # flattening only remove one level of nesting at a time
        d: Result[Result[Result[str, int], int], int] = Ok(Ok(Ok("hello")))
        assert Ok(Ok("hello")) == d.flatten()
        assert Ok("hello") == d.flatten().flatten()
        ```
    """

iter()

Returns an Iterator over the possibly contained value.

Returns:

Type Description
PyoIterator[T]

PyoIterator[T]: An Iterator over the Ok value, or empty if Err.

Example
from pyochain import Ok, Err, Some

assert Ok(7).iter().next() == Some(7)
assert Err("nothing!").iter().next().is_none()
Source code in pyochain/core/_result.pyi
201
202
203
204
205
206
207
208
209
210
211
212
213
214
def iter(self) -> PyoIterator[T]:
    """Returns an `Iterator` over the possibly contained value.

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

    Example:
        ```python
        from pyochain import Ok, Err, Some

        assert Ok(7).iter().next() == Some(7)
        assert Err("nothing!").iter().next().is_none()
        ```
    """

map_star(func)

map_star(func: Callable[[Any], R]) -> Result[R, E]
map_star(func: Callable[[T1, T2], R]) -> Result[R, E]
map_star(func: Callable[[T1, T2, T3], R]) -> Result[R, E]
map_star(
    func: Callable[[T1, T2, T3, T4], R],
) -> Result[R, E]
map_star(
    func: Callable[[T1, T2, T3, T4, T5], R],
) -> Result[R, E]
map_star(
    func: Callable[[T1, T2, T3, T4, T5, T6], R],
) -> Result[R, E]
map_star(
    func: Callable[[T1, T2, T3, T4, T5, T6, T7], R],
) -> Result[R, E]
map_star(
    func: Callable[[T1, T2, T3, T4, T5, T6, T7, T8], R],
) -> Result[R, E]
map_star(
    func: Callable[[T1, T2, T3, T4, T5, T6, T7, T8, T9], R],
) -> Result[R, E]
map_star(
    func: Callable[
        [T1, T2, T3, T4, T5, T6, T7, T8, T9, T10], R
    ],
) -> Result[R, E]

Maps a Result[tuple, E] to Result[R, E] by unpacking the tuple.

Done by applying a function to a contained Ok value (which is expected to be a tuple).

Parameters:

Name Type Description Default
func Callable[..., R]

The function to apply to the unpacked Ok value.

required

Returns:

Type Description
Result[R, E]

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

Example
from pyochain import Ok, Err
from operator import add

assert Ok((2, 3)).map_star(add).unwrap() == 5
assert Err("error").map_star(add).unwrap_err() == "error"
Source code in pyochain/core/_result.pyi
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
def map_star[U: tuple[Any, ...], R](
    self: ResultType[U, E],
    func: Callable[..., R],
) -> Result[R, E]:
    """Maps a `Result[tuple, E]` to `Result[R, E]` by unpacking the tuple.

    Done by applying a function to a contained `Ok` value (which is expected to be a `tuple`).

    Args:
        func (Callable[..., R]): The function to apply to the unpacked `Ok` value.

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

    Example:
        ```python
        from pyochain import Ok, Err
        from operator import add

        assert Ok((2, 3)).map_star(add).unwrap() == 5
        assert Err("error").map_star(add).unwrap_err() == "error"
        ```
    """

and_then_star(func)

and_then_star(
    func: Callable[[T1], Result[R, S]],
) -> Result[R, S]
and_then_star(
    func: Callable[[T1, T2], Result[R, S]],
) -> Result[R, S]
and_then_star(
    func: Callable[[T1, T2, T3], Result[R, S]],
) -> Result[R, S]
and_then_star(
    func: Callable[[T1, T2, T3, T4], Result[R, S]],
) -> Result[R, S]
and_then_star(
    func: Callable[[T1, T2, T3, T4, T5], Result[R, S]],
) -> Result[R, S]
and_then_star(
    func: Callable[[T1, T2, T3, T4, T5, T6], Result[R, S]],
) -> Result[R, S]
and_then_star(
    func: Callable[
        [T1, T2, T3, T4, T5, T6, T7], Result[R, S]
    ],
) -> Result[R, S]
and_then_star(
    func: Callable[
        [T1, T2, T3, T4, T5, T6, T7, T8], Result[R, S]
    ],
) -> Result[R, S]
and_then_star(
    func: Callable[
        [T1, T2, T3, T4, T5, T6, T7, T8, T9], Result[R, S]
    ],
) -> Result[R, S]
and_then_star(
    func: Callable[
        [T1, T2, T3, T4, T5, T6, T7, T8, T9, T10],
        Result[R, S],
    ],
) -> Result[R, S]

Calls a function if the result is Ok, unpacking the tuple.

Done by applying a function to a contained Ok value (which is expected to be a tuple).

Parameters:

Name Type Description Default
func Callable[..., Result[R, E]]

The function to call with the unpacked Ok value.

required

Returns:

Type Description
Result[R, E]

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

Example
from pyochain import Ok, Err, Result

def to_str(x: int, y: int) -> Result[str, str]:
    return Ok(f"{x},{y}")

assert Ok((2, 3)).and_then_star(to_str).unwrap() == "2,3"
assert Err("error").and_then_star(to_str).unwrap_err() == "error"
Source code in pyochain/core/_result.pyi
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
def and_then_star[U: tuple[Any, ...], R](
    self: Result[U, E], func: Callable[..., Result[R, E]]
) -> Result[R, E]:
    """Calls a function if the result is `Ok`, unpacking the tuple.

    Done by applying a function to a contained `Ok` value (which is expected to be a tuple).

    Args:
        func (Callable[..., Result[R, E]]): The function to call with the unpacked `Ok` value.

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

    Example:
        ```python
        from pyochain import Ok, Err, Result

        def to_str(x: int, y: int) -> Result[str, str]:
            return Ok(f"{x},{y}")

        assert Ok((2, 3)).and_then_star(to_str).unwrap() == "2,3"
        assert Err("error").and_then_star(to_str).unwrap_err() == "error"
        ```
    """

is_ok()

Returns True if the result is Ok.

Returns:

Name Type Description
bool bool

True if the result is an Ok variant, False otherwise.

Example
from pyochain import Ok, Err, Result

x: Result[int, str] = Ok(2)
assert x.is_ok()

y: Result[int, str] = Err("Some error message")
assert not y.is_ok()
Source code in pyochain/core/_result.pyi
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
def is_ok(self) -> bool:
    """Returns `True` if the result is `Ok`.

    Returns:
        bool: `True` if the result is an `Ok` variant, `False` otherwise.

    Example:
        ```python
        from pyochain import Ok, Err, Result

        x: Result[int, str] = Ok(2)
        assert x.is_ok()

        y: Result[int, str] = Err("Some error message")
        assert not y.is_ok()
        ```
    """

is_err()

Returns True if the result is Err.

Returns:

Name Type Description
bool bool

True if the result is an Err variant, False otherwise.

Example
from pyochain import Ok, Err, Result

x: Result[int, str] = Ok(2)
assert not x.is_err()

y: Result[int, str] = Err("Some error message")
assert y.is_err()
Source code in pyochain/core/_result.pyi
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
def is_err(self) -> bool:
    """Returns `True` if the result is `Err`.

    Returns:
        bool: `True` if the result is an `Err` variant, `False` otherwise.

    Example:
        ```python
        from pyochain import Ok, Err, Result

        x: Result[int, str] = Ok(2)
        assert not x.is_err()

        y: Result[int, str] = Err("Some error message")
        assert y.is_err()
        ```
    """

unwrap()

Returns the contained Ok value.

raises ResultUnwrapError if the result is Err.

Returns:

Name Type Description
T T

The contained Ok value.

Example
from pyochain import Ok, Err, ResultUnwrapError

assert Ok(2).unwrap() == 2

try:
    _ = Err(1).unwrap()
except ResultUnwrapError as e:
    assert str(e) == "called `unwrap` on an `Err`: 1"
Source code in pyochain/core/_result.pyi
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
def unwrap(self) -> T:
    """Returns the contained `Ok` value.

    raises `ResultUnwrapError` if the result is `Err`.

    Returns:
        T: The contained `Ok` value.

    Example:
        ```python
        from pyochain import Ok, Err, ResultUnwrapError

        assert Ok(2).unwrap() == 2

        try:
            _ = Err(1).unwrap()
        except ResultUnwrapError as e:
            assert str(e) == "called `unwrap` on an `Err`: 1"
        ```
    """

unwrap_err()

Returns the contained Err value.

raises ResultUnwrapError if the result is Ok.

Returns:

Name Type Description
E E

The contained Err value.

Example

from pyochain import Err

assert Err("emergency failure").unwrap_err() == "emergency failure"
from pyochain import Ok, ResultUnwrapError

try:
    _ = Ok(2).unwrap_err()
except ResultUnwrapError as e:
    assert str(e) == "called `unwrap_err` on Ok"

Source code in pyochain/core/_result.pyi
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
def unwrap_err(self) -> E:
    """Returns the contained `Err` value.

    raises `ResultUnwrapError` if the result is `Ok`.

    Returns:
        E: The contained `Err` value.

    Example:
        ```python
        from pyochain import Err

        assert Err("emergency failure").unwrap_err() == "emergency failure"
        ```
        ```python
        from pyochain import Ok, ResultUnwrapError

        try:
            _ = Ok(2).unwrap_err()
        except ResultUnwrapError as e:
            assert str(e) == "called `unwrap_err` on Ok"
        ```
    """

map_or_else(ok, err)

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
from pyochain import Ok, Err

k = 21
assert Ok("foo").map_or_else(len, lambda e: k * 2) == 3
assert Err("bar").map_or_else(len, lambda e: k * 2) == 42
Source code in pyochain/core/_result.pyi
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
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
        from pyochain import Ok, Err

        k = 21
        assert Ok("foo").map_or_else(len, lambda e: k * 2) == 3
        assert Err("bar").map_or_else(len, lambda e: k * 2) == 42
        ```
    """

expect(msg)

Returns the contained Ok value.

raises ResultUnwrapError 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.

Example
from pyochain import Err, Ok, ResultUnwrapError

assert Ok(2).expect("No error") == 2
try:
    _ = Err(1).expect("Unexpected error")
except ResultUnwrapError as e:
    assert str(e) == "Unexpected error: 1"
Source code in pyochain/core/_result.pyi
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
def expect(self, msg: str) -> T:
    """Returns the contained `Ok` value.

    raises `ResultUnwrapError` 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.

    Example:
        ```python
        from pyochain import Err, Ok, ResultUnwrapError

        assert Ok(2).expect("No error") == 2
        try:
            _ = Err(1).expect("Unexpected error")
        except ResultUnwrapError as e:
            assert str(e) == "Unexpected error: 1"
        ```
    """

expect_err(msg)

Returns the contained Err value.

raises ResultUnwrapError 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.

Example
from pyochain import Err, Ok, ResultUnwrapError

e = Err("emergency failure").expect_err("Testing expect_err")
assert str(e) == "emergency failure"
try:
    _ = Ok(10).expect_err("Testing expect_err")
except ResultUnwrapError as e:
    assert str(e) == "Testing expect_err: expected Err, got Ok(10)"
Source code in pyochain/core/_result.pyi
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
def expect_err(self, msg: str) -> E:
    """Returns the contained `Err` value.

    raises `ResultUnwrapError` 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.

    Example:
        ```python
        from pyochain import Err, Ok, ResultUnwrapError

        e = Err("emergency failure").expect_err("Testing expect_err")
        assert str(e) == "emergency failure"
        try:
            _ = Ok(10).expect_err("Testing expect_err")
        except ResultUnwrapError as e:
            assert str(e) == "Testing expect_err: expected Err, got Ok(10)"
        ```
    """

unwrap_or(default)

Returns the contained Ok value or a provided default.

Parameters:

Name Type Description Default
default D

The value to return if the result is Err.

required

Returns:

Type Description
T | D

T | D: The contained Ok value or the provided default.

Example
from pyochain import Ok, Err

assert Ok(2).unwrap_or(10) == 2
assert Err("error").unwrap_or(10) == 10
Source code in pyochain/core/_result.pyi
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
def unwrap_or[D](self, default: D) -> T | D:
    """Returns the contained `Ok` value or a provided default.

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

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

    Example:
        ```python
        from pyochain import Ok, Err

        assert Ok(2).unwrap_or(10) == 2
        assert Err("error").unwrap_or(10) == 10
        ```
    """

unwrap_or_else(fn, *args, **kwargs)

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

Parameters:

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

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:

Type Description
T | O

T | O: The contained Ok value or the result of the function.

Example
from pyochain import Ok, Err

assert Ok(2).unwrap_or_else(len) == 2
assert Err("foo").unwrap_or_else(len) == 3
Source code in pyochain/core/_result.pyi
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
def unwrap_or_else[**P, O](
    self, fn: Callable[Concatenate[E, P], O], *args: P.args, **kwargs: P.kwargs
) -> T | O:
    """Returns the contained `Ok` value or computes it from a function.

    Args:
        fn (Callable[Concatenate[E, P], O]): 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 | O: The contained `Ok` value or the result of the function.

    Example:
        ```python
        from pyochain import Ok, Err

        assert Ok(2).unwrap_or_else(len) == 2
        assert Err("foo").unwrap_or_else(len) == 3
        ```
    """

map(fn, *args, **kwargs)

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
from pyochain import Ok, Err

assert Ok(2).map(lambda x: x * 2).unwrap() == 4
assert Err("error").map(lambda x: x * 2).unwrap_err() == "error"
Source code in pyochain/core/_result.pyi
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
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
        from pyochain import Ok, Err

        assert Ok(2).map(lambda x: x * 2).unwrap() == 4
        assert Err("error").map(lambda x: x * 2).unwrap_err() == "error"
        ```
    """

map_err(fn, *args, **kwargs)

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
from pyochain import Ok, Err

assert Ok(2).map_err(len).unwrap() == 2
assert Err("foo").map_err(len).unwrap_err() == 3
Source code in pyochain/core/_result.pyi
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
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
        from pyochain import Ok, Err

        assert Ok(2).map_err(len).unwrap() == 2
        assert Err("foo").map_err(len).unwrap_err() == 3
        ```
    """

inspect(fn, *args, **kwargs)

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
from pyochain import Ok, Vec

seen = Vec[int](())
assert Ok(2).inspect(lambda x: seen.append(x)).unwrap() == 2
assert seen == Vec(2)
Source code in pyochain/core/_result.pyi
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
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
        from pyochain import Ok, Vec

        seen = Vec[int](())
        assert Ok(2).inspect(lambda x: seen.append(x)).unwrap() == 2
        assert seen == Vec(2)
        ```
    """

inspect_err(fn, *args, **kwargs)

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
from pyochain import Err, Vec

seen = Vec[str](())
res = Err("oops").inspect_err(lambda e: seen.append(e)).unwrap_err()
assert res == "oops"
assert seen == Vec(["oops"])
Source code in pyochain/core/_result.pyi
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
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
        from pyochain import Err, Vec

        seen = Vec[str](())
        res = Err("oops").inspect_err(lambda e: seen.append(e)).unwrap_err()
        assert res == "oops"
        assert seen == Vec(["oops"])
        ```
    """

and_(res)

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, O]

The result to return if the original result is Ok.

required

Returns:

Type Description
Result[U, E | O]

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

Example
from pyochain import Ok, Err

x = Ok(2)
y = Err("late error")
assert x.and_(y).unwrap_err() == "late error"

x = Err("early error")
y = Ok("foo")
assert x.and_(y).unwrap_err() == "early error"

x = Err("not a 2")
y = Err("late error")
assert x.and_(y).unwrap_err() == "not a 2"

x = Ok(2)
y = Ok("different result type")
assert x.and_(y).unwrap() == "different result type"
Source code in pyochain/core/_result.pyi
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
def and_[O, U](self, res: Result[U, O]) -> Result[U, E | O]:
    """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, O]): The result to return if the original result is `Ok`.

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

    Example:
        ```python
        from pyochain import Ok, Err

        x = Ok(2)
        y = Err("late error")
        assert x.and_(y).unwrap_err() == "late error"

        x = Err("early error")
        y = Ok("foo")
        assert x.and_(y).unwrap_err() == "early error"

        x = Err("not a 2")
        y = Err("late error")
        assert x.and_(y).unwrap_err() == "not a 2"

        x = Ok(2)
        y = Ok("different result type")
        assert x.and_(y).unwrap() == "different result type"
        ```
    """

and_then(fn, *args, **kwargs)

and_then(fn: type[ResultType[Any, Any]]) -> Result[T1, E1]
and_then(
    fn: Callable[Concatenate[T1, P], Result[R, E1]],
    *args: P.args,
    **kwargs: P.kwargs,
) -> Result[R, E1]

Calls fn if the result is [Ok], otherwise returns the [Err] value of self.

This function can be used for control flow based on Result values.

Parameters:

Name Type Description Default
fn Callable[Concatenate[T1, P], Result[R, E1]] | type[ResultType[Any, Any]]

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, E1]

Result[R, E1]: The result of calling fn if the original result is Ok, otherwise the original Err.

Examples:

from pyochain import Ok, Err, Result

def try_mul_to_str(x: int) -> Result[str, str]:
    if x < 100_000:
        return Ok(str(x * x))
    else:
        return Err("overflow")

assert Ok(2).and_then(try_mul_to_str) == Ok("4")
assert Ok(1_000_000).and_then(try_mul_to_str) == Err("overflow")
assert Err("hi").and_then(try_mul_to_str) == Err("hi")

Often used to chain fallible operations that may return [Err].

from pyochain import Option, Some, NONE
from pathlib import Path

CONFIG = Path("pyproject")

def run(value: int = 10, path: Option[str] = NONE) -> Result[float, str]:
    return (
        check_toml(path.map(Path).unwrap_or(CONFIG))
        .map(lambda _: value)
        .and_then(parse_int)
        .and_then(reciprocal)
    )

def check_toml(path: Path) -> Result[None, str]:
    p = path.with_suffix(".toml")
    if p.exists():
        return Ok(None)
    else:
        return Err(f"File {p} does not exist")

def parse_int(s: str) -> Result[int, str]:
    try:
        return Ok(int(s))
    except ValueError:
        return Err(f"'{s}' is not a valid int")

def reciprocal(x: int) -> Result[float, str]:
    if x == 0:
        return Err("division by zero")
    else:
        return Ok(1 / x)

assert run() == Ok(0.1)
assert run(path=Some("ruff")) == Ok(0.1)
assert run(path=Some("bad")) == Err("File bad.toml does not exist")
assert run(value=0) == Err("division by zero")
assert run(value="hi") == Err("'hi' is not a valid int")
Source code in pyochain/core/_result.pyi
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
def and_then[**P, T1, E1, R](
    self: Result[T1, E1],
    fn: Callable[Concatenate[T1, P], Result[R, E1]] | type[ResultType[Any, Any]],
    *args: P.args,
    **kwargs: P.kwargs,
) -> Result[R, E1]:
    """Calls `fn` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.

    This function can be used for control flow based on `Result` values.

    Args:
        fn (Callable[Concatenate[T1, P], Result[R, E1]] | type[ResultType[Any, Any]]): 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, E1]: The result of calling `fn` if the original result is `Ok`, otherwise the original `Err`.

    Examples:
        ```python
        from pyochain import Ok, Err, Result

        def try_mul_to_str(x: int) -> Result[str, str]:
            if x < 100_000:
                return Ok(str(x * x))
            else:
                return Err("overflow")

        assert Ok(2).and_then(try_mul_to_str) == Ok("4")
        assert Ok(1_000_000).and_then(try_mul_to_str) == Err("overflow")
        assert Err("hi").and_then(try_mul_to_str) == Err("hi")
        ```

        Often used to chain fallible operations that may return [`Err`].

        ```python
        from pyochain import Option, Some, NONE
        from pathlib import Path

        CONFIG = Path("pyproject")

        def run(value: int = 10, path: Option[str] = NONE) -> Result[float, str]:
            return (
                check_toml(path.map(Path).unwrap_or(CONFIG))
                .map(lambda _: value)
                .and_then(parse_int)
                .and_then(reciprocal)
            )

        def check_toml(path: Path) -> Result[None, str]:
            p = path.with_suffix(".toml")
            if p.exists():
                return Ok(None)
            else:
                return Err(f"File {p} does not exist")

        def parse_int(s: str) -> Result[int, str]:
            try:
                return Ok(int(s))
            except ValueError:
                return Err(f"'{s}' is not a valid int")

        def reciprocal(x: int) -> Result[float, str]:
            if x == 0:
                return Err("division by zero")
            else:
                return Ok(1 / x)

        assert run() == Ok(0.1)
        assert run(path=Some("ruff")) == Ok(0.1)
        assert run(path=Some("bad")) == Err("File bad.toml does not exist")
        assert run(value=0) == Err("division by zero")
        assert run(value="hi") == Err("'hi' is not a valid int")
        ```
    """

or_else(fn, *args, **kwargs)

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[object, R]]

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, R]

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

Example
from pyochain import Ok, Err, Result

def fallback(e: str) -> Result[int, str]:
    return Ok(len(e))

assert Ok(2).or_else(fallback).unwrap() == 2
assert Err("foo").or_else(fallback).unwrap() == 3
Source code in pyochain/core/_result.pyi
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
def or_else[**P, R](
    self,
    fn: Callable[Concatenate[E, P], Result[object, R]],
    *args: P.args,
    **kwargs: P.kwargs,
) -> Result[T, R]:
    """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[object, R]]): 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, R]: The original `Ok` value, or the result of the function if `Err`.

    Example:
        ```python
        from pyochain import Ok, Err, Result

        def fallback(e: str) -> Result[int, str]:
            return Ok(len(e))

        assert Ok(2).or_else(fallback).unwrap() == 2
        assert Err("foo").or_else(fallback).unwrap() == 3
        ```
    """

ok()

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
from pyochain import Ok, Err, Some

assert Ok(2).ok().unwrap() == 2
assert Err("error").ok().is_none()
Source code in pyochain/core/_result.pyi
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
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
            from pyochain import Ok, Err, Some

            assert Ok(2).ok().unwrap() == 2
            assert Err("error").ok().is_none()
            ```
    """

err()

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
from pyochain import Ok, Err, Some

assert Ok(2).err().is_none()
assert Err("error").err().unwrap() == "error"
Source code in pyochain/core/_result.pyi
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
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
        from pyochain import Ok, Err, Some

        assert Ok(2).err().is_none()
        assert Err("error").err().unwrap() == "error"
        ```
    """

is_ok_and(pred, *args, **kwargs)

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
from pyochain import Ok, Err

assert Ok(2).is_ok_and(lambda x: x > 1)
assert not Ok(0).is_ok_and(lambda x: x > 1)
assert not Err("err").is_ok_and(lambda x: x > 1)
Source code in pyochain/core/_result.pyi
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
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
        from pyochain import Ok, Err

        assert Ok(2).is_ok_and(lambda x: x > 1)
        assert not Ok(0).is_ok_and(lambda x: x > 1)
        assert not Err("err").is_ok_and(lambda x: x > 1)
        ```
    """

is_err_and(pred, *args, **kwargs)

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
from pyochain import Err, Ok

assert Err("foo").is_err_and(lambda e: len(e) == 3)
assert not Err("bar").is_err_and(lambda e: e == "baz")
assert not Ok(2).is_err_and(lambda e: True)
Source code in pyochain/core/_result.pyi
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
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
        from pyochain import Err, Ok

        assert Err("foo").is_err_and(lambda e: len(e) == 3)
        assert not Err("bar").is_err_and(lambda e: e == "baz")
        assert not Ok(2).is_err_and(lambda e: True)
        ```
    """

map_or(default, f, *args, **kwargs)

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
from pyochain import Ok, Err

assert Ok(2).map_or(10, lambda x: x * 2) == 4
assert Err("err").map_or(10, lambda x: x * 2) == 10
Source code in pyochain/core/_result.pyi
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
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
        from pyochain import Ok, Err

        assert Ok(2).map_or(10, lambda x: x * 2) == 4
        assert Err("err").map_or(10, lambda x: x * 2) == 10
        ```
    """

transpose()

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

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

The mapping is as follows:

  • Ok(Some(v)) becomes Some(Ok(v))
  • Ok(NONE) becomes NONE
  • Err(e) becomes Some(Err(e))

Returns:

Type Description
Option[Result[S, E]]

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

Example
from pyochain import Ok, Err, Some, NONE

assert Ok(Some(2)).transpose().unwrap().unwrap() == 2
assert Ok(NONE).transpose().is_none()
assert Err("err").transpose().unwrap().unwrap_err() == "err"
Source code in pyochain/core/_result.pyi
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
def transpose[S](self: ResultType[Option[S], E]) -> Option[Result[S, E]]:
    """Transposes a Result containing an Option into an Option containing a Result.

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

    The mapping is as follows:

    - `Ok(Some(v))` becomes `Some(Ok(v))`
    - `Ok(NONE)` becomes `NONE`
    - `Err(e)` becomes `Some(Err(e))`

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

    Example:
        ```python
        from pyochain import Ok, Err, Some, NONE

        assert Ok(Some(2)).transpose().unwrap().unwrap() == 2
        assert Ok(NONE).transpose().is_none()
        assert Err("err").transpose().unwrap().unwrap_err() == "err"
        ```
    """

or_(res)

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

Parameters:

Name Type Description Default
res Result[S, F]

The result to return if the original result is Err.

required

Returns:

Type Description
Result[T | S, F]

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

Example
from pyochain import Ok, Err

assert Ok(2).or_(Err("late error")).unwrap() == 2
assert Err("early error").or_(Ok(2)).unwrap() == 2
assert Err("not a 2").or_(Err("late error")).unwrap_err() == "late error"
assert Ok(2).or_(Ok(100)).unwrap() == 2
Source code in pyochain/core/_result.pyi
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
def or_[S, F](self, res: Result[S, F]) -> Result[T | S, F]:
    """Returns res if the result is `Err`, otherwise returns the `Ok` value of **self**.

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

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

    Example:
        ```python
        from pyochain import Ok, Err

        assert Ok(2).or_(Err("late error")).unwrap() == 2
        assert Err("early error").or_(Ok(2)).unwrap() == 2
        assert Err("not a 2").or_(Err("late error")).unwrap_err() == "late error"
        assert Ok(2).or_(Ok(100)).unwrap() == 2
        ```
    """