Skip to content

OptionType

Bases: Pipe, Protocol


              flowchart TD
              pyochain.core._option.OptionType[OptionType]
              pyochain.abc._mixins.Pipe[Pipe]

                              pyochain.abc._mixins.Pipe --> pyochain.core._option.OptionType
                


              click pyochain.core._option.OptionType href "" "pyochain.core._option.OptionType"
              click pyochain.abc._mixins.Pipe href "" "pyochain.abc._mixins.Pipe"
            

OptionType is the common interface for an optional value.

Option[T] is the union of Some[T] and Null[T], and represents a value that can only have two states:

  • Some(value)
  • Null().

This is a common type in Rust, and is used to represent values that may be absent.

In python, this is best tought of a an union type T | None, but with additional methods to operate on the contained value in a functional style.

Option[T] and/or T | None types are very useful, as they have a number of uses:

  • Initial values
  • Union types
  • Return value where None is returned on error
  • Optional class fields
  • Optional function arguments

The fact that T | None is a very common pattern in python, but without a dedicated structure/handling, leads to:

  • a lot of boilerplate code
  • potential bugs (even with type checkers)
  • less readable code (where does the None come from? is it expected?).

Option[T] instances are commonly paired with pattern matching. This allow to query the presence of a value and take action, always accounting for the None case.

Example
from pyochain import Option, Some, Null

def divide(a: int, b: int) -> Option[int]:
    if b == 0:
        return Null()
    return Some(a // b)

assert divide(10, 2) == Some(5)
assert divide(10, 0).is_none()
Source code in pyochain/core/_option.pyi
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
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
957
958
959
960
961
962
963
964
965
966
967
@type_check_only
class OptionType[T](Pipe, Protocol):
    """OptionType is the common interface for an optional value.

    `Option[T]` is the union of `Some[T]` and `Null[T]`, and represents a value that can only have two states:

    - `Some(value)`
    - `Null()`.

    This is a common type in Rust, and is used to represent values that may be absent.

    In python, this is best tought of a an union type `T | None`,
    but with additional methods to operate on the contained value in a functional style.

    `Option[T]` and/or `T | None` types are very useful, as they have a number of uses:

    - Initial values
    - Union types
    - Return value where None is returned on error
    - Optional class fields
    - Optional function arguments

    The fact that `T | None` is a very common pattern in python,
    but without a dedicated structure/handling, leads to:

    - a lot of boilerplate code
    - potential bugs (even with type checkers)
    - less readable code (where does the None come from? is it expected?).

    `Option[T]` instances are commonly paired with pattern matching.
    This allow to query the presence of a value and take action, always accounting for the None case.

    Example:
        ```python
        from pyochain import Option, Some, Null

        def divide(a: int, b: int) -> Option[int]:
            if b == 0:
                return Null()
            return Some(a // b)

        assert divide(10, 2) == Some(5)
        assert divide(10, 0).is_none()
        ```
    """

    def __bool__(self) -> Never:
        """Prevent implicit `Some|None` value checking in boolean contexts.

        Always raises `TypeError` to prevent implicit `Some|None` value checking, as the `Option` truthiness is ambiguous.

        Are we checking the presence or absence of the value, or the truthiness of the contained value?

        Use `Option::{is_some, is_none, filter, map_if, or_else}`, and others alike for combining control flow with `Option` values.

        Returns:
            Never: Always raises `TypeError`.

        Example:
            ```python
            from pyochain import Some
            import pytest

            x = Some(42)
            with pytest.raises(TypeError):
                bool(x)
            ```
        """

    @override
    def __eq__(self, other: object) -> bool:
        """Checks if this `Option` and *other* are equal.

        A plain Python `None` is considered equal to a `pyochain.Null` instance.

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

        Returns:
            bool: `True` if both instances are equal, `False` otherwise.

        See Also:
            [`Option::eq`][eq] for a type-safe, performant version that only accepts `Option[T]` instances.

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

            assert Some(42) == Some(42)
            assert Some(42) != Some(21)
            assert Some(42) != NONE
            assert NONE == NONE
            assert Some(42) != 42
            ```
        """

    def flatten[T1](self: Option[Option[T1]]) -> Option[T1]:
        """Flattens a nested `Option`.

        Converts an `Option[Option[U]]` into an `Option[U]` by removing one level of nesting.

        Equivalent to `Option.and_then(lambda x: x)`.

        Returns:
            Option[T1]: The flattened option.

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

            assert Some(Some(42)).flatten() == Some(42)
            assert Some(NONE).flatten().is_none()
            assert NONE.flatten().is_none()
            ```
        """

    @overload
    def map_star[R](
        self: Option[tuple[Any]],
        func: Callable[[Any], R],
    ) -> Option[R]: ...
    @overload
    def map_star[T1, T2, R](
        self: Option[tuple[T1, T2]],
        func: Callable[[T1, T2], R],
    ) -> Option[R]: ...
    @overload
    def map_star[T1, T2, T3, R](
        self: Option[tuple[T1, T2, T3]],
        func: Callable[[T1, T2, T3], R],
    ) -> Option[R]: ...
    @overload
    def map_star[T1, T2, T3, T4, R](
        self: Option[tuple[T1, T2, T3, T4]],
        func: Callable[[T1, T2, T3, T4], R],
    ) -> Option[R]: ...
    @overload
    def map_star[T1, T2, T3, T4, T5, R](
        self: Option[tuple[T1, T2, T3, T4, T5]],
        func: Callable[[T1, T2, T3, T4, T5], R],
    ) -> Option[R]: ...
    @overload
    def map_star[T1, T2, T3, T4, T5, T6, R](
        self: Option[tuple[T1, T2, T3, T4, T5, T6]],
        func: Callable[[T1, T2, T3, T4, T5, T6], R],
    ) -> Option[R]: ...
    @overload
    def map_star[T1, T2, T3, T4, T5, T6, T7, R](
        self: Option[tuple[T1, T2, T3, T4, T5, T6, T7]],
        func: Callable[[T1, T2, T3, T4, T5, T6, T7], R],
    ) -> Option[R]: ...
    @overload
    def map_star[T1, T2, T3, T4, T5, T6, T7, T8, R](
        self: Option[tuple[T1, T2, T3, T4, T5, T6, T7, T8]],
        func: Callable[[T1, T2, T3, T4, T5, T6, T7, T8], R],
    ) -> Option[R]: ...
    @overload
    def map_star[T1, T2, T3, T4, T5, T6, T7, T8, T9, R](
        self: Option[tuple[T1, T2, T3, T4, T5, T6, T7, T8, T9]],
        func: Callable[[T1, T2, T3, T4, T5, T6, T7, T8, T9], R],
    ) -> Option[R]: ...
    @overload
    def map_star[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, R](
        self: Option[tuple[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]],
        func: Callable[[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10], R],
    ) -> Option[R]: ...
    def map_star[U: Iterable[Any], R](
        self: OptionType[U], func: Callable[..., R]
    ) -> Option[R]:
        """Maps an `Option[Iterable]` to `Option[U]` by unpacking the iterable into the function.

        Done by applying a function to a contained `Some` value,
        leaving a `None` value untouched.

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

        Returns:
            Option[R]: A new `Option` with the mapped value if `Some`, otherwise `None`.

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

            assert Some((2, 3)).map_star(lambda x, y: x + y) == Some(5)
            assert NONE.map_star(lambda x, y: x + y).is_none()
            ```
        """

    @overload
    def and_then_star[R](
        self: Option[tuple[Any]],
        func: Callable[[Any], Option[R]],
    ) -> Option[R]: ...
    @overload
    def and_then_star[T1, T2, R](
        self: Option[tuple[T1, T2]],
        func: Callable[[T1, T2], Option[R]],
    ) -> Option[R]: ...
    @overload
    def and_then_star[T1, T2, T3, R](
        self: Option[tuple[T1, T2, T3]],
        func: Callable[[T1, T2, T3], Option[R]],
    ) -> Option[R]: ...
    @overload
    def and_then_star[T1, T2, T3, T4, R](
        self: Option[tuple[T1, T2, T3, T4]],
        func: Callable[[T1, T2, T3, T4], Option[R]],
    ) -> Option[R]: ...
    @overload
    def and_then_star[T1, T2, T3, T4, T5, R](
        self: Option[tuple[T1, T2, T3, T4, T5]],
        func: Callable[[T1, T2, T3, T4, T5], Option[R]],
    ) -> Option[R]: ...
    @overload
    def and_then_star[T1, T2, T3, T4, T5, T6, R](
        self: Option[tuple[T1, T2, T3, T4, T5, T6]],
        func: Callable[[T1, T2, T3, T4, T5, T6], Option[R]],
    ) -> Option[R]: ...
    @overload
    def and_then_star[T1, T2, T3, T4, T5, T6, T7, R](
        self: Option[tuple[T1, T2, T3, T4, T5, T6, T7]],
        func: Callable[[T1, T2, T3, T4, T5, T6, T7], Option[R]],
    ) -> Option[R]: ...
    @overload
    def and_then_star[T1, T2, T3, T4, T5, T6, T7, T8, R](
        self: Option[tuple[T1, T2, T3, T4, T5, T6, T7, T8]],
        func: Callable[[T1, T2, T3, T4, T5, T6, T7, T8], Option[R]],
    ) -> Option[R]: ...
    @overload
    def and_then_star[T1, T2, T3, T4, T5, T6, T7, T8, T9, R](
        self: Option[tuple[T1, T2, T3, T4, T5, T6, T7, T8, T9]],
        func: Callable[[T1, T2, T3, T4, T5, T6, T7, T8, T9], Option[R]],
    ) -> Option[R]: ...
    @overload
    def and_then_star[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, R](
        self: Option[tuple[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]],
        func: Callable[[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10], Option[R]],
    ) -> Option[R]: ...
    def and_then_star[U: Iterable[Any], R](
        self: OptionType[U], func: Callable[..., Option[R]]
    ) -> Option[R]:
        """Calls a function if the option is `Some`, unpacking the iterable into the function.

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

        Returns:
            Option[R]: The result of the function if `Some`, otherwise `None`.

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

            assert Some((2, 3)).and_then_star(lambda x, y: Some(x + y)) == Some(5)
            assert NONE.and_then_star(lambda x, y: Some(x + y)).is_none()
            ```
        """

    def ne(self, other: Option[object]) -> bool:
        """Checks if two `Option[T]` instances are not equal.

        Args:
            other (Option[object]): The other `Option[object]` instance to compare with.

        Returns:
            bool: `True` if both instances are not equal, `False` otherwise.

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

            assert Some(42).ne(Some(21))
            assert not Some(42).ne(Some(42))
            assert Some(42).ne(NONE)
            assert not NONE.ne(NONE)
            ```
        """

    def eq(self, other: Option[object]) -> bool:
        """Checks if two `Option[T]` instances are equal.

        Note:
            This method behave similarly to `__eq__`, but only accepts `Option[T]` instances as argument.

            This avoids runtime isinstance checks (we check for boolean `is_some()`, which is a simple function call), and is more type-safe.

        Args:
            other (Option[object]): The other `Option[T]` instance to compare with.

        Returns:
            bool: `True` if both instances are equal, `False` otherwise.

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

            assert Some(42).eq(Some(42))
            assert not Some(42).eq(Some(21))
            assert not Some(42).eq(NONE)
            assert NONE.eq(NONE)
            ```
        """

    def is_some(self) -> bool:
        """Returns `True` if the option is a `Some` value.

        Returns:
            bool: `True` if the option is a `Some` variant, `False` otherwise.

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

            assert Some(2).is_some()
            assert not NONE.is_some()
            ```
        """

    def is_some_and[**P](
        self,
        predicate: Callable[Concatenate[T, P], bool],
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> bool:
        """Returns true if the option is a Some and the value inside of it matches a predicate.

        Args:
            predicate (Callable[Concatenate[T, P], bool]): The predicate to apply to the contained value.
            *args (P.args): Additional positional arguments to pass to predicate.
            **kwargs (P.kwargs): Additional keyword arguments to pass to predicate.

        Returns:
            bool: `True` if the option is `Some` and the predicate returns `True` for the contained value, `False` otherwise.

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

            x = Some(2)
            assert x.is_some_and(lambda x: x > 1)

            x = Some(0)
            assert not x.is_some_and(lambda x: x > 1)

            x = NONE
            assert not x.is_some_and(lambda x: x > 1)

            x = Some("hello")
            assert x.is_some_and(lambda x: len(x) > 1)
            ```
        """

    def is_none(self) -> bool:
        """Returns `True` if the option is a `None` value.

        Returns:
            bool: `True` if the option is a `_None` variant, `False` otherwise.

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

            x = Some(2)
            assert not x.is_none()
            y = NONE

            assert y.is_none()
            ```
        """

    def is_none_or[**P](
        self, func: Callable[Concatenate[T, P], bool], *args: P.args, **kwargs: P.kwargs
    ) -> bool:
        """Returns true if the option is a None or the value inside of it matches a predicate.

        Args:
            func (Callable[Concatenate[T, P], bool]): The predicate to apply to the contained value.
            *args (P.args): Additional positional arguments to pass to func.
            **kwargs (P.kwargs): Additional keyword arguments to pass to func.

        Returns:
            bool: `True` if the option is `None` or the predicate returns `True` for the contained value, `False` otherwise.

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

            assert Some(2).is_none_or(lambda x: x > 1)
            assert not Some(0).is_none_or(lambda x: x > 1)
            assert NONE.is_none_or(lambda x: x > 1)
            assert Some("hello").is_none_or(lambda x: len(x) > 1)
            ```
        """

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

        raises `OptionUnwrapError` if the option is `None`.

        Returns:
            T: The contained `Some` value.

        Example:
            ```python
            from pyochain import Some, NONE, OptionUnwrapError

            assert Some("car").unwrap() == "car"

            try:
                NONE.unwrap()
            except OptionUnwrapError as e:
                assert str(e) == "called `unwrap` on a `None`"
            ```
        """

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

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

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

        Returns:
            T: The contained `Some` value.

        Example:
            ```python
            from pyochain import Some, NONE, OptionUnwrapError

            assert Some("value").expect("fruits are healthy") == "value"

            try:
                NONE.expect("fruits are healthy")
            except OptionUnwrapError as e:
                assert str(e) == "fruits are healthy (called `expect` on a `None`)"
            ```
        """

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

        Args:
            default (S): The value to return if the result is `None`.

        Returns:
            T | S: The contained `Some` value or the provided default.

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

            assert Some("car").unwrap_or("bike") == "car"
            assert NONE.unwrap_or("bike") == "bike"
            ```
        """

    def unwrap_or_else[S](self, f: Callable[[], S]) -> T | S:
        """Returns the contained `Some` value or computes it from a function.

        Args:
            f (Callable[[], S]): A function that returns a default value if the result is `None`.

        Returns:
            T | S: The contained `Some` value or the result of the function.

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

            k = 10

            assert Some(4).unwrap_or_else(lambda: 2 * k) == 4
            assert NONE.unwrap_or_else(lambda: 2 * k) == 20
            ```
        """

    def map[**P, R](
        self, f: Callable[Concatenate[T, P], R], *args: P.args, **kwargs: P.kwargs
    ) -> Option[R]:
        """Maps an `Option[T]` to `Option[U]`.

        Done by applying a function to a contained `Some` value,
        leaving a `None` value untouched.

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

        Returns:
            Option[R]: A new `Option` with the mapped value if `Some`, otherwise `None`.

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

            assert Some("Hello, World!").map(len) == Some(13)
            assert NONE.map(len).is_none()
            ```
        """

    def and_[U](self, optb: Option[U]) -> Option[U]:
        """Returns `NONE` if the option is `NONE`, otherwise returns optb.

        This is similar to `and_then`, except that the value is passed directly instead of through a closure.

        Args:
            optb (Option[U]): The option to return if the original option is `NONE`

        Returns:
            Option[U]: `NONE` if the original option is `NONE`, otherwise `optb`.

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

            assert Some(2).and_(NONE).is_none()
            assert NONE.and_(Some("foo")).is_none()
            assert Some(2).and_(Some("foo")) == Some("foo")
            assert NONE.and_(NONE).is_none()
            ```
        """

    def or_[S](self, optb: Option[S]) -> Option[T | S]:
        """Returns the option if it contains a value, otherwise returns optb.

        Args:
            optb (Option[S]): The option to return if the original option is `NONE`.

        Returns:
            Option[T | S]: The original option if it is `Some`, otherwise `optb`.

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

            assert Some(2).or_(NONE) == Some(2)
            assert NONE.or_(Some(100)) == Some(100)
            assert Some(2).or_(Some(100)) == Some(2)
            assert NONE.or_(NONE).is_none()
            ```
        """

    def and_then[**P, R](
        self,
        f: Callable[Concatenate[T, P], Option[R]],
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> Option[R]:
        """Calls a function if the option is `Some`, otherwise returns `None`.

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

        Returns:
            Option[R]: The result of the function if `Some`, otherwise `None`.

        Example:
            ```python
            from pyochain import Some, NONE, Option

            def sq(x: int) -> Option[int]:
                return Some(x * x)

            def nope(x: int) -> Option[int]:
                return NONE

            assert Some(2).and_then(sq).and_then(sq) == Some(16)
            assert Some(2).and_then(sq).and_then(nope).is_none()
            assert Some(2).and_then(nope).and_then(sq).is_none()
            assert NONE.and_then(sq).and_then(sq).is_none()
            ```
        """

    def or_else[S](self, f: Callable[[], Option[S]]) -> Option[T | S]:
        """Returns the `Option[T]` if it contains a value, otherwise calls a function and returns the result.

        Args:
            f (Callable[[], Option[S]]): The function to call if the option is `None`.

        Returns:
            Option[T | S]: The original `Option` if it is `Some`, otherwise the result of the function.

        Example:
            ```python
            from pyochain import Some, NONE, Option

            def nobody() -> Option[str]:
                return NONE

            def vikings() -> Option[str]:
                return Some("vikings")

            assert Some("barbarians").or_else(vikings) == Some("barbarians")
            assert NONE.or_else(vikings) == Some("vikings")
            assert NONE.or_else(nobody).is_none()
            ```
        """

    def ok_or[E](self, err: E) -> Result[T, E]:
        """Converts the option to a `Result`.

        Args:
            err (E): The error value to use if the option is `NONE`.

        Returns:
            Result[T, E]: `Ok(v)` if `Some(v)`, otherwise `Err(err)`.

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

            assert Some(1).ok_or("fail").unwrap() == 1
            assert NONE.ok_or("fail").unwrap_err() == "fail"
            ```
        """

    def ok_or_else[E](self, err: Callable[[], E]) -> Result[T, E]:
        """Converts the option to a Result.

        Args:
            err (Callable[[], E]): A function returning the error value if the option is NONE.

        Returns:
            Result[T, E]: Ok(v) if Some(v), otherwise Err(err()).

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

            assert Some(1).ok_or_else(lambda: "fail").unwrap() == 1
            assert NONE.ok_or_else(lambda: "fail").unwrap_err() == "fail"
            ```
        """

    def map_or[**P, R](
        self,
        default: R,
        f: Callable[Concatenate[T, P], R],
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> R:
        """Returns the result of applying a function to the contained value if Some, otherwise returns the default value.

        Args:
            default (R): The default value to return if NONE.
            f (Callable[Concatenate[T, P], R]): The function to apply to the contained value.
            *args (P.args): Additional positional arguments to pass to f.
            **kwargs (P.kwargs): Additional keyword arguments to pass to f.

        Returns:
            R: The result of f(self.unwrap()) if Some, otherwise default.

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

            assert Some(2).map_or(0, lambda x: x * 10) == 20
            assert NONE.map_or(0, lambda x: x * 10) == 0
            ```
        """

    def map_or_else[**P, R](self, default: Callable[[], R], f: Callable[[T], R]) -> R:
        """Returns the result of applying a function to the contained value if Some, otherwise computes a default value.

        Args:
            default (Callable[[], R]): A function returning the default value if NONE.
            f (Callable[[T], R]): The function to apply to the contained value.

        Returns:
            R: The result of f(self.unwrap()) if Some, otherwise default().

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

            assert Some(2).map_or_else(lambda: 0, lambda x: x * 10) == 20
            assert NONE.map_or_else(lambda: 0, lambda x: x * 10) == 0
            ```
        """

    def filter[**P](
        self,
        predicate: Callable[Concatenate[T, P], object],
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> Option[T]:
        """Returns `NONE` if the option is `NONE`, otherwise calls predicate with the wrapped value.

        This function works similar to `PyoIterator::filter` in the sense that we only keep the value if it matches a predicate.

        You can imagine the `Option[T]` being an iterator over one or zero elements.

        Args:
            predicate (Callable[Concatenate[T, P], object]): The predicate to apply to the contained value.
            *args (P.args): Additional positional arguments to pass to predicate.
            **kwargs (P.kwargs): Additional keyword arguments to pass to predicate.

        Returns:
            Option[T]: `Some[T]` if predicate returns true (where T is the wrapped value), `NONE` if predicate returns false.


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

            def is_even(n: int) -> bool:
                return n % 2 == 0

            assert NONE.filter(is_even).is_none()
            assert Some(3).filter(is_even).is_none()
            assert Some(4).filter(is_even) == Some(4)
            ```
        """

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

        - If the option is `Some(value)`, the iterator yields `value`.
        - If the option is `NONE`, the iterator yields nothing.

        Equivalent to `Iter(self.unwrap())` if `Some`, or `Iter()` if `NONE`.

        Returns:
            PyoIterator[T]: An `Iterator` over the optional value.

        Example:
            ```python
            from pyochain import Some, NONE, Iter

            assert Some(42).iter().next() == Some(42)
            assert NONE.iter().next().is_none()
            assert Iter(42).next() == Some(42).iter().next()
            ```
        """

    def inspect[**P](
        self, f: Callable[Concatenate[T, P], object], *args: P.args, **kwargs: P.kwargs
    ) -> Option[T]:
        """Applies a function to the contained `Some` value, returning the original `Option`.

        This allows side effects (logging, debugging, metrics, etc.) on the wrapped value without changing it.

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

        Returns:
            Option[T]: The original option, unchanged.

        Example:
            ```python
            from pyochain import Some, NONE, Vec

            seen = Vec[int]([])

            assert Some(2).inspect(lambda x: seen.append(x)) == Some(2)
            assert seen == Vec(2)

            assert NONE.inspect(lambda x: seen.append(x)).is_none()
            assert seen == Vec(2)
            ```
        """

    def unzip[S, U](self: Option[tuple[S, U]]) -> tuple[Option[S], Option[U]]:
        """Unzips an `Option` of a tuple into a tuple of `Option`s.

        If the option is `Some((a, b))`, this method returns `(Some(a), Some(b))`.
        If the option is `NONE`, it returns `(NONE, NONE)`.

        Returns:
            tuple[Option[S], Option[U]]: A tuple containing two options.

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

            assert Some((1, "a")).unzip() == (Some(1), Some("a"))
            assert NONE.unzip() == (NONE, NONE)
            ```
        """

    def zip[U](self, other: Option[U]) -> Option[tuple[T, U]]:
        """Returns an `Option[tuple[T, U]]` containing a tuple of the values if both options are `Some`, otherwise returns `NONE`.

        Args:
            other (Option[U]): The other option to zip with.

        Returns:
            Option[tuple[T, U]]: Some((self, other)) if both are Some, otherwise NONE.

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

            assert Some(1).zip(Some("a")) == Some((1, "a"))
            assert Some(1).zip(NONE).is_none()
            assert NONE.zip(Some("a")).is_none()
            ```
        """

    def zip_with[U, R](self, other: Option[U], f: Callable[[T, U], R]) -> Option[R]:
        """Zips `self` and another `Option` with function `f`.

        If `self` is `Some(s)` and other is `Some(o)`, this method returns `Some(f(s, o))`.

        Otherwise, `NONE` is returned.

        Args:
            other (Option[U]): The second option.
            f (Callable[[T, U], R]): The function to apply to the unwrapped values.

        Returns:
            Option[R]: The resulting option after applying the function.

        Example:
            ```python
            from dataclasses import dataclass
            from pyochain import Some, NONE

            @dataclass
            class Point:
                x: float
                y: float

            x = Some(17.5)
            y = Some(42.7)

            assert x.zip_with(y, Point) == Some(Point(x=17.5, y=42.7))
            assert x.zip_with(NONE, Point).is_none()
            assert NONE.zip_with(y, Point).is_none()
            ```
        """

    def reduce[O, R](self, other: Option[O], func: Callable[[T, O], R]) -> Option[R]:
        """Reduces two options into one, using the provided function if both are Some.

        If **self** is `Some(s)` and **other** is `Some(o)`, this method returns `Some(func(s, o))`.

        Otherwise, if only one of **self** and **other** is `Some`, that value is returned.

        If both **self** and **other** are `NONE`, `NONE` is returned.

        Args:
            other (Option[O]): The second option.
            func (Callable[[T, O], R]): The function to apply to the unwrapped values.

        Returns:
            Option[R]: The resulting option after reduction.

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

            s12 = Some(12)
            s17 = Some(17)

            def add(a: int, b: int) -> int:
                return a + b

            assert s12.reduce(s17, add) == Some(29)
            assert s12.reduce(NONE, add) == Some(12)
            assert NONE.reduce(s17, add) == Some(17)
            assert NONE.reduce(NONE, add).is_none()

            def concat(a: str, b: str) -> str:
                return a + b

            a = Some("Hello, ").reduce(Some("World!"), concat)
            assert a == Some("Hello, World!")
            b = Some("I am ").reduce(Some(26), lambda a, b: a + str(b))
            assert b == Some("I am 26")
            ```
        """

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

        The mapping is as follows:

        - `Some(Ok[T])` is mapped to `Ok(Some[T])`
        - `Some(Err[E])` is mapped to `Err[E]`
        - `NONE` is mapped to `Ok(NONE)`

        Returns:
            Result[Option[S], E]: The transposed result.

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

            assert Some(Ok(5)).transpose().unwrap().unwrap() == 5
            assert NONE.transpose().unwrap().is_none()
            assert Some(Err("error")).transpose().unwrap_err() == "error"
            ```
        """

    def xor[O](self, optb: Option[object]) -> Option[T]:
        """Returns `Some` if exactly one of **self**, optb is `Some`, otherwise returns `NONE`.

        Args:
            optb (Option[object]): The other option to compare with.

        Returns:
            Option[T]: `Some` value if exactly one option is `Some`, otherwise `NONE`.

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

            assert Some(2).xor(NONE).unwrap() == 2
            assert NONE.xor(Some(2)).unwrap() == 2
            assert Some(2).xor(Some(2)).is_none()
            assert NONE.xor(NONE).is_none()
            assert Some("hello").xor(Some(1)).is_none()
            ```
        """

    def unwrap_or_none(self) -> T | None:
        """Returns the contained `Some` value or `None`.

        This is a convenience method for interoperability with APIs that use `None` to represent the absence of a value,

        e.g. when interacting with standard Python libraries, or external dependencies.

        This is **NOT** the recommended use for handling `Option` in any code that can be controlled, as it defeats the purpose of using `Option` for explicit handling of optional values.

        Returns:
            T | None: The contained `Some` value or `None`.

        Example:
            ```python
            from pyochain import Option, Some, NONE

            assert NONE.unwrap_or_none() is None
            assert Some(42).unwrap_or_none() == 42
            ```
        """

__bool__()

Prevent implicit Some|None value checking in boolean contexts.

Always raises TypeError to prevent implicit Some|None value checking, as the Option truthiness is ambiguous.

Are we checking the presence or absence of the value, or the truthiness of the contained value?

Use Option::{is_some, is_none, filter, map_if, or_else}, and others alike for combining control flow with Option values.

Returns:

Name Type Description
Never Never

Always raises TypeError.

Example
from pyochain import Some
import pytest

x = Some(42)
with pytest.raises(TypeError):
    bool(x)
Source code in pyochain/core/_option.pyi
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
def __bool__(self) -> Never:
    """Prevent implicit `Some|None` value checking in boolean contexts.

    Always raises `TypeError` to prevent implicit `Some|None` value checking, as the `Option` truthiness is ambiguous.

    Are we checking the presence or absence of the value, or the truthiness of the contained value?

    Use `Option::{is_some, is_none, filter, map_if, or_else}`, and others alike for combining control flow with `Option` values.

    Returns:
        Never: Always raises `TypeError`.

    Example:
        ```python
        from pyochain import Some
        import pytest

        x = Some(42)
        with pytest.raises(TypeError):
            bool(x)
        ```
    """

__eq__(other)

Checks if this Option and other are equal.

A plain Python None is considered equal to a pyochain.Null instance.

Parameters:

Name Type Description Default
other object

The other object to compare with.

required

Returns:

Name Type Description
bool bool

True if both instances are equal, False otherwise.

See Also

Option::eq for a type-safe, performant version that only accepts Option[T] instances.

Example
from pyochain import Some, NONE

assert Some(42) == Some(42)
assert Some(42) != Some(21)
assert Some(42) != NONE
assert NONE == NONE
assert Some(42) != 42
Source code in pyochain/core/_option.pyi
 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
@override
def __eq__(self, other: object) -> bool:
    """Checks if this `Option` and *other* are equal.

    A plain Python `None` is considered equal to a `pyochain.Null` instance.

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

    Returns:
        bool: `True` if both instances are equal, `False` otherwise.

    See Also:
        [`Option::eq`][eq] for a type-safe, performant version that only accepts `Option[T]` instances.

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

        assert Some(42) == Some(42)
        assert Some(42) != Some(21)
        assert Some(42) != NONE
        assert NONE == NONE
        assert Some(42) != 42
        ```
    """

flatten()

Flattens a nested Option.

Converts an Option[Option[U]] into an Option[U] by removing one level of nesting.

Equivalent to Option.and_then(lambda x: x).

Returns:

Type Description
Option[T1]

Option[T1]: The flattened option.

Example
from pyochain import Some, NONE

assert Some(Some(42)).flatten() == Some(42)
assert Some(NONE).flatten().is_none()
assert NONE.flatten().is_none()
Source code in pyochain/core/_option.pyi
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
def flatten[T1](self: Option[Option[T1]]) -> Option[T1]:
    """Flattens a nested `Option`.

    Converts an `Option[Option[U]]` into an `Option[U]` by removing one level of nesting.

    Equivalent to `Option.and_then(lambda x: x)`.

    Returns:
        Option[T1]: The flattened option.

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

        assert Some(Some(42)).flatten() == Some(42)
        assert Some(NONE).flatten().is_none()
        assert NONE.flatten().is_none()
        ```
    """

map_star(func)

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

Maps an Option[Iterable] to Option[U] by unpacking the iterable into the function.

Done by applying a function to a contained Some value, leaving a None value untouched.

Parameters:

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

The function to apply to the unpacked Some value.

required

Returns:

Type Description
Option[R]

Option[R]: A new Option with the mapped value if Some, otherwise None.

Example
from pyochain import Some, NONE

assert Some((2, 3)).map_star(lambda x, y: x + y) == Some(5)
assert NONE.map_star(lambda x, y: x + y).is_none()
Source code in pyochain/core/_option.pyi
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
def map_star[U: Iterable[Any], R](
    self: OptionType[U], func: Callable[..., R]
) -> Option[R]:
    """Maps an `Option[Iterable]` to `Option[U]` by unpacking the iterable into the function.

    Done by applying a function to a contained `Some` value,
    leaving a `None` value untouched.

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

    Returns:
        Option[R]: A new `Option` with the mapped value if `Some`, otherwise `None`.

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

        assert Some((2, 3)).map_star(lambda x, y: x + y) == Some(5)
        assert NONE.map_star(lambda x, y: x + y).is_none()
        ```
    """

and_then_star(func)

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

Calls a function if the option is Some, unpacking the iterable into the function.

Parameters:

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

The function to call with the unpacked Some value.

required

Returns:

Type Description
Option[R]

Option[R]: The result of the function if Some, otherwise None.

Example
from pyochain import Some, NONE

assert Some((2, 3)).and_then_star(lambda x, y: Some(x + y)) == Some(5)
assert NONE.and_then_star(lambda x, y: Some(x + y)).is_none()
Source code in pyochain/core/_option.pyi
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
def and_then_star[U: Iterable[Any], R](
    self: OptionType[U], func: Callable[..., Option[R]]
) -> Option[R]:
    """Calls a function if the option is `Some`, unpacking the iterable into the function.

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

    Returns:
        Option[R]: The result of the function if `Some`, otherwise `None`.

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

        assert Some((2, 3)).and_then_star(lambda x, y: Some(x + y)) == Some(5)
        assert NONE.and_then_star(lambda x, y: Some(x + y)).is_none()
        ```
    """

ne(other)

Checks if two Option[T] instances are not equal.

Parameters:

Name Type Description Default
other Option[object]

The other Option[object] instance to compare with.

required

Returns:

Name Type Description
bool bool

True if both instances are not equal, False otherwise.

Example
from pyochain import Some, NONE

assert Some(42).ne(Some(21))
assert not Some(42).ne(Some(42))
assert Some(42).ne(NONE)
assert not NONE.ne(NONE)
Source code in pyochain/core/_option.pyi
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
def ne(self, other: Option[object]) -> bool:
    """Checks if two `Option[T]` instances are not equal.

    Args:
        other (Option[object]): The other `Option[object]` instance to compare with.

    Returns:
        bool: `True` if both instances are not equal, `False` otherwise.

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

        assert Some(42).ne(Some(21))
        assert not Some(42).ne(Some(42))
        assert Some(42).ne(NONE)
        assert not NONE.ne(NONE)
        ```
    """

eq(other)

Checks if two Option[T] instances are equal.

Note

This method behave similarly to __eq__, but only accepts Option[T] instances as argument.

This avoids runtime isinstance checks (we check for boolean is_some(), which is a simple function call), and is more type-safe.

Parameters:

Name Type Description Default
other Option[object]

The other Option[T] instance to compare with.

required

Returns:

Name Type Description
bool bool

True if both instances are equal, False otherwise.

Example
from pyochain import Some, NONE

assert Some(42).eq(Some(42))
assert not Some(42).eq(Some(21))
assert not Some(42).eq(NONE)
assert NONE.eq(NONE)
Source code in pyochain/core/_option.pyi
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
def eq(self, other: Option[object]) -> bool:
    """Checks if two `Option[T]` instances are equal.

    Note:
        This method behave similarly to `__eq__`, but only accepts `Option[T]` instances as argument.

        This avoids runtime isinstance checks (we check for boolean `is_some()`, which is a simple function call), and is more type-safe.

    Args:
        other (Option[object]): The other `Option[T]` instance to compare with.

    Returns:
        bool: `True` if both instances are equal, `False` otherwise.

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

        assert Some(42).eq(Some(42))
        assert not Some(42).eq(Some(21))
        assert not Some(42).eq(NONE)
        assert NONE.eq(NONE)
        ```
    """

is_some()

Returns True if the option is a Some value.

Returns:

Name Type Description
bool bool

True if the option is a Some variant, False otherwise.

Example
from pyochain import Some, NONE

assert Some(2).is_some()
assert not NONE.is_some()
Source code in pyochain/core/_option.pyi
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def is_some(self) -> bool:
    """Returns `True` if the option is a `Some` value.

    Returns:
        bool: `True` if the option is a `Some` variant, `False` otherwise.

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

        assert Some(2).is_some()
        assert not NONE.is_some()
        ```
    """

is_some_and(predicate, *args, **kwargs)

Returns true if the option is a Some and the value inside of it matches a predicate.

Parameters:

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

The predicate to apply to the contained value.

required
*args P.args

Additional positional arguments to pass to predicate.

()
**kwargs P.kwargs

Additional keyword arguments to pass to predicate.

{}

Returns:

Name Type Description
bool bool

True if the option is Some and the predicate returns True for the contained value, False otherwise.

Example
from pyochain import Some, NONE

x = Some(2)
assert x.is_some_and(lambda x: x > 1)

x = Some(0)
assert not x.is_some_and(lambda x: x > 1)

x = NONE
assert not x.is_some_and(lambda x: x > 1)

x = Some("hello")
assert x.is_some_and(lambda x: len(x) > 1)
Source code in pyochain/core/_option.pyi
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
def is_some_and[**P](
    self,
    predicate: Callable[Concatenate[T, P], bool],
    *args: P.args,
    **kwargs: P.kwargs,
) -> bool:
    """Returns true if the option is a Some and the value inside of it matches a predicate.

    Args:
        predicate (Callable[Concatenate[T, P], bool]): The predicate to apply to the contained value.
        *args (P.args): Additional positional arguments to pass to predicate.
        **kwargs (P.kwargs): Additional keyword arguments to pass to predicate.

    Returns:
        bool: `True` if the option is `Some` and the predicate returns `True` for the contained value, `False` otherwise.

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

        x = Some(2)
        assert x.is_some_and(lambda x: x > 1)

        x = Some(0)
        assert not x.is_some_and(lambda x: x > 1)

        x = NONE
        assert not x.is_some_and(lambda x: x > 1)

        x = Some("hello")
        assert x.is_some_and(lambda x: len(x) > 1)
        ```
    """

is_none()

Returns True if the option is a None value.

Returns:

Name Type Description
bool bool

True if the option is a _None variant, False otherwise.

Example
from pyochain import Some, NONE

x = Some(2)
assert not x.is_none()
y = NONE

assert y.is_none()
Source code in pyochain/core/_option.pyi
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
def is_none(self) -> bool:
    """Returns `True` if the option is a `None` value.

    Returns:
        bool: `True` if the option is a `_None` variant, `False` otherwise.

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

        x = Some(2)
        assert not x.is_none()
        y = NONE

        assert y.is_none()
        ```
    """

is_none_or(func, *args, **kwargs)

Returns true if the option is a None or the value inside of it matches a predicate.

Parameters:

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

The predicate to apply to the contained value.

required
*args P.args

Additional positional arguments to pass to func.

()
**kwargs P.kwargs

Additional keyword arguments to pass to func.

{}

Returns:

Name Type Description
bool bool

True if the option is None or the predicate returns True for the contained value, False otherwise.

Example
from pyochain import Some, NONE

assert Some(2).is_none_or(lambda x: x > 1)
assert not Some(0).is_none_or(lambda x: x > 1)
assert NONE.is_none_or(lambda x: x > 1)
assert Some("hello").is_none_or(lambda x: len(x) > 1)
Source code in pyochain/core/_option.pyi
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
def is_none_or[**P](
    self, func: Callable[Concatenate[T, P], bool], *args: P.args, **kwargs: P.kwargs
) -> bool:
    """Returns true if the option is a None or the value inside of it matches a predicate.

    Args:
        func (Callable[Concatenate[T, P], bool]): The predicate to apply to the contained value.
        *args (P.args): Additional positional arguments to pass to func.
        **kwargs (P.kwargs): Additional keyword arguments to pass to func.

    Returns:
        bool: `True` if the option is `None` or the predicate returns `True` for the contained value, `False` otherwise.

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

        assert Some(2).is_none_or(lambda x: x > 1)
        assert not Some(0).is_none_or(lambda x: x > 1)
        assert NONE.is_none_or(lambda x: x > 1)
        assert Some("hello").is_none_or(lambda x: len(x) > 1)
        ```
    """

unwrap()

Returns the contained Some value.

raises OptionUnwrapError if the option is None.

Returns:

Name Type Description
T T

The contained Some value.

Example
from pyochain import Some, NONE, OptionUnwrapError

assert Some("car").unwrap() == "car"

try:
    NONE.unwrap()
except OptionUnwrapError as e:
    assert str(e) == "called `unwrap` on a `None`"
Source code in pyochain/core/_option.pyi
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
def unwrap(self) -> T:
    """Returns the contained `Some` value.

    raises `OptionUnwrapError` if the option is `None`.

    Returns:
        T: The contained `Some` value.

    Example:
        ```python
        from pyochain import Some, NONE, OptionUnwrapError

        assert Some("car").unwrap() == "car"

        try:
            NONE.unwrap()
        except OptionUnwrapError as e:
            assert str(e) == "called `unwrap` on a `None`"
        ```
    """

expect(msg)

Returns the contained Some value.

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

Parameters:

Name Type Description Default
msg str

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

required

Returns:

Name Type Description
T T

The contained Some value.

Example
from pyochain import Some, NONE, OptionUnwrapError

assert Some("value").expect("fruits are healthy") == "value"

try:
    NONE.expect("fruits are healthy")
except OptionUnwrapError as e:
    assert str(e) == "fruits are healthy (called `expect` on a `None`)"
Source code in pyochain/core/_option.pyi
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
def expect(self, msg: str) -> T:
    """Returns the contained `Some` value.

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

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

    Returns:
        T: The contained `Some` value.

    Example:
        ```python
        from pyochain import Some, NONE, OptionUnwrapError

        assert Some("value").expect("fruits are healthy") == "value"

        try:
            NONE.expect("fruits are healthy")
        except OptionUnwrapError as e:
            assert str(e) == "fruits are healthy (called `expect` on a `None`)"
        ```
    """

unwrap_or(default)

Returns the contained Some value or a provided default.

Parameters:

Name Type Description Default
default S

The value to return if the result is None.

required

Returns:

Type Description
T | S

T | S: The contained Some value or the provided default.

Example
from pyochain import Some, NONE

assert Some("car").unwrap_or("bike") == "car"
assert NONE.unwrap_or("bike") == "bike"
Source code in pyochain/core/_option.pyi
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
def unwrap_or[S](self, default: S) -> T | S:
    """Returns the contained `Some` value or a provided default.

    Args:
        default (S): The value to return if the result is `None`.

    Returns:
        T | S: The contained `Some` value or the provided default.

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

        assert Some("car").unwrap_or("bike") == "car"
        assert NONE.unwrap_or("bike") == "bike"
        ```
    """

unwrap_or_else(f)

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

Parameters:

Name Type Description Default
f Callable[[], S]

A function that returns a default value if the result is None.

required

Returns:

Type Description
T | S

T | S: The contained Some value or the result of the function.

Example
from pyochain import Some, NONE

k = 10

assert Some(4).unwrap_or_else(lambda: 2 * k) == 4
assert NONE.unwrap_or_else(lambda: 2 * k) == 20
Source code in pyochain/core/_option.pyi
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
def unwrap_or_else[S](self, f: Callable[[], S]) -> T | S:
    """Returns the contained `Some` value or computes it from a function.

    Args:
        f (Callable[[], S]): A function that returns a default value if the result is `None`.

    Returns:
        T | S: The contained `Some` value or the result of the function.

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

        k = 10

        assert Some(4).unwrap_or_else(lambda: 2 * k) == 4
        assert NONE.unwrap_or_else(lambda: 2 * k) == 20
        ```
    """

map(f, *args, **kwargs)

Maps an Option[T] to Option[U].

Done by applying a function to a contained Some value, leaving a None value untouched.

Parameters:

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

The function to apply to the Some value.

required
*args P.args

Additional positional arguments to pass to f.

()
**kwargs P.kwargs

Additional keyword arguments to pass to f.

{}

Returns:

Type Description
Option[R]

Option[R]: A new Option with the mapped value if Some, otherwise None.

Example
from pyochain import Some, NONE

assert Some("Hello, World!").map(len) == Some(13)
assert NONE.map(len).is_none()
Source code in pyochain/core/_option.pyi
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
def map[**P, R](
    self, f: Callable[Concatenate[T, P], R], *args: P.args, **kwargs: P.kwargs
) -> Option[R]:
    """Maps an `Option[T]` to `Option[U]`.

    Done by applying a function to a contained `Some` value,
    leaving a `None` value untouched.

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

    Returns:
        Option[R]: A new `Option` with the mapped value if `Some`, otherwise `None`.

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

        assert Some("Hello, World!").map(len) == Some(13)
        assert NONE.map(len).is_none()
        ```
    """

and_(optb)

Returns NONE if the option is NONE, otherwise returns optb.

This is similar to and_then, except that the value is passed directly instead of through a closure.

Parameters:

Name Type Description Default
optb Option[U]

The option to return if the original option is NONE

required

Returns:

Type Description
Option[U]

Option[U]: NONE if the original option is NONE, otherwise optb.

Example
from pyochain import Some, NONE

assert Some(2).and_(NONE).is_none()
assert NONE.and_(Some("foo")).is_none()
assert Some(2).and_(Some("foo")) == Some("foo")
assert NONE.and_(NONE).is_none()
Source code in pyochain/core/_option.pyi
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
def and_[U](self, optb: Option[U]) -> Option[U]:
    """Returns `NONE` if the option is `NONE`, otherwise returns optb.

    This is similar to `and_then`, except that the value is passed directly instead of through a closure.

    Args:
        optb (Option[U]): The option to return if the original option is `NONE`

    Returns:
        Option[U]: `NONE` if the original option is `NONE`, otherwise `optb`.

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

        assert Some(2).and_(NONE).is_none()
        assert NONE.and_(Some("foo")).is_none()
        assert Some(2).and_(Some("foo")) == Some("foo")
        assert NONE.and_(NONE).is_none()
        ```
    """

or_(optb)

Returns the option if it contains a value, otherwise returns optb.

Parameters:

Name Type Description Default
optb Option[S]

The option to return if the original option is NONE.

required

Returns:

Type Description
Option[T | S]

Option[T | S]: The original option if it is Some, otherwise optb.

Example
from pyochain import Some, NONE

assert Some(2).or_(NONE) == Some(2)
assert NONE.or_(Some(100)) == Some(100)
assert Some(2).or_(Some(100)) == Some(2)
assert NONE.or_(NONE).is_none()
Source code in pyochain/core/_option.pyi
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
def or_[S](self, optb: Option[S]) -> Option[T | S]:
    """Returns the option if it contains a value, otherwise returns optb.

    Args:
        optb (Option[S]): The option to return if the original option is `NONE`.

    Returns:
        Option[T | S]: The original option if it is `Some`, otherwise `optb`.

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

        assert Some(2).or_(NONE) == Some(2)
        assert NONE.or_(Some(100)) == Some(100)
        assert Some(2).or_(Some(100)) == Some(2)
        assert NONE.or_(NONE).is_none()
        ```
    """

and_then(f, *args, **kwargs)

Calls a function if the option is Some, otherwise returns None.

Parameters:

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

The function to call with the Some value.

required
*args P.args

Additional positional arguments to pass to f.

()
**kwargs P.kwargs

Additional keyword arguments to pass to f.

{}

Returns:

Type Description
Option[R]

Option[R]: The result of the function if Some, otherwise None.

Example
from pyochain import Some, NONE, Option

def sq(x: int) -> Option[int]:
    return Some(x * x)

def nope(x: int) -> Option[int]:
    return NONE

assert Some(2).and_then(sq).and_then(sq) == Some(16)
assert Some(2).and_then(sq).and_then(nope).is_none()
assert Some(2).and_then(nope).and_then(sq).is_none()
assert NONE.and_then(sq).and_then(sq).is_none()
Source code in pyochain/core/_option.pyi
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
def and_then[**P, R](
    self,
    f: Callable[Concatenate[T, P], Option[R]],
    *args: P.args,
    **kwargs: P.kwargs,
) -> Option[R]:
    """Calls a function if the option is `Some`, otherwise returns `None`.

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

    Returns:
        Option[R]: The result of the function if `Some`, otherwise `None`.

    Example:
        ```python
        from pyochain import Some, NONE, Option

        def sq(x: int) -> Option[int]:
            return Some(x * x)

        def nope(x: int) -> Option[int]:
            return NONE

        assert Some(2).and_then(sq).and_then(sq) == Some(16)
        assert Some(2).and_then(sq).and_then(nope).is_none()
        assert Some(2).and_then(nope).and_then(sq).is_none()
        assert NONE.and_then(sq).and_then(sq).is_none()
        ```
    """

or_else(f)

Returns the Option[T] if it contains a value, otherwise calls a function and returns the result.

Parameters:

Name Type Description Default
f Callable[[], Option[S]]

The function to call if the option is None.

required

Returns:

Type Description
Option[T | S]

Option[T | S]: The original Option if it is Some, otherwise the result of the function.

Example
from pyochain import Some, NONE, Option

def nobody() -> Option[str]:
    return NONE

def vikings() -> Option[str]:
    return Some("vikings")

assert Some("barbarians").or_else(vikings) == Some("barbarians")
assert NONE.or_else(vikings) == Some("vikings")
assert NONE.or_else(nobody).is_none()
Source code in pyochain/core/_option.pyi
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
def or_else[S](self, f: Callable[[], Option[S]]) -> Option[T | S]:
    """Returns the `Option[T]` if it contains a value, otherwise calls a function and returns the result.

    Args:
        f (Callable[[], Option[S]]): The function to call if the option is `None`.

    Returns:
        Option[T | S]: The original `Option` if it is `Some`, otherwise the result of the function.

    Example:
        ```python
        from pyochain import Some, NONE, Option

        def nobody() -> Option[str]:
            return NONE

        def vikings() -> Option[str]:
            return Some("vikings")

        assert Some("barbarians").or_else(vikings) == Some("barbarians")
        assert NONE.or_else(vikings) == Some("vikings")
        assert NONE.or_else(nobody).is_none()
        ```
    """

ok_or(err)

Converts the option to a Result.

Parameters:

Name Type Description Default
err E

The error value to use if the option is NONE.

required

Returns:

Type Description
Result[T, E]

Result[T, E]: Ok(v) if Some(v), otherwise Err(err).

Example
from pyochain import Some, NONE, Ok

assert Some(1).ok_or("fail").unwrap() == 1
assert NONE.ok_or("fail").unwrap_err() == "fail"
Source code in pyochain/core/_option.pyi
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
def ok_or[E](self, err: E) -> Result[T, E]:
    """Converts the option to a `Result`.

    Args:
        err (E): The error value to use if the option is `NONE`.

    Returns:
        Result[T, E]: `Ok(v)` if `Some(v)`, otherwise `Err(err)`.

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

        assert Some(1).ok_or("fail").unwrap() == 1
        assert NONE.ok_or("fail").unwrap_err() == "fail"
        ```
    """

ok_or_else(err)

Converts the option to a Result.

Parameters:

Name Type Description Default
err Callable[[], E]

A function returning the error value if the option is NONE.

required

Returns:

Type Description
Result[T, E]

Result[T, E]: Ok(v) if Some(v), otherwise Err(err()).

Example
from pyochain import Some, NONE, Ok, Err

assert Some(1).ok_or_else(lambda: "fail").unwrap() == 1
assert NONE.ok_or_else(lambda: "fail").unwrap_err() == "fail"
Source code in pyochain/core/_option.pyi
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
def ok_or_else[E](self, err: Callable[[], E]) -> Result[T, E]:
    """Converts the option to a Result.

    Args:
        err (Callable[[], E]): A function returning the error value if the option is NONE.

    Returns:
        Result[T, E]: Ok(v) if Some(v), otherwise Err(err()).

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

        assert Some(1).ok_or_else(lambda: "fail").unwrap() == 1
        assert NONE.ok_or_else(lambda: "fail").unwrap_err() == "fail"
        ```
    """

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

Returns the result of applying a function to the contained value if Some, otherwise returns the default value.

Parameters:

Name Type Description Default
default R

The default value to return if NONE.

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

The function to apply to the contained 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

The result of f(self.unwrap()) if Some, otherwise default.

Example
from pyochain import Some, NONE

assert Some(2).map_or(0, lambda x: x * 10) == 20
assert NONE.map_or(0, lambda x: x * 10) == 0
Source code in pyochain/core/_option.pyi
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
def map_or[**P, R](
    self,
    default: R,
    f: Callable[Concatenate[T, P], R],
    *args: P.args,
    **kwargs: P.kwargs,
) -> R:
    """Returns the result of applying a function to the contained value if Some, otherwise returns the default value.

    Args:
        default (R): The default value to return if NONE.
        f (Callable[Concatenate[T, P], R]): The function to apply to the contained value.
        *args (P.args): Additional positional arguments to pass to f.
        **kwargs (P.kwargs): Additional keyword arguments to pass to f.

    Returns:
        R: The result of f(self.unwrap()) if Some, otherwise default.

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

        assert Some(2).map_or(0, lambda x: x * 10) == 20
        assert NONE.map_or(0, lambda x: x * 10) == 0
        ```
    """

map_or_else(default, f)

Returns the result of applying a function to the contained value if Some, otherwise computes a default value.

Parameters:

Name Type Description Default
default Callable[[], R]

A function returning the default value if NONE.

required
f Callable[[T], R]

The function to apply to the contained value.

required

Returns:

Name Type Description
R R

The result of f(self.unwrap()) if Some, otherwise default().

Example
from pyochain import Some, NONE

assert Some(2).map_or_else(lambda: 0, lambda x: x * 10) == 20
assert NONE.map_or_else(lambda: 0, lambda x: x * 10) == 0
Source code in pyochain/core/_option.pyi
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
def map_or_else[**P, R](self, default: Callable[[], R], f: Callable[[T], R]) -> R:
    """Returns the result of applying a function to the contained value if Some, otherwise computes a default value.

    Args:
        default (Callable[[], R]): A function returning the default value if NONE.
        f (Callable[[T], R]): The function to apply to the contained value.

    Returns:
        R: The result of f(self.unwrap()) if Some, otherwise default().

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

        assert Some(2).map_or_else(lambda: 0, lambda x: x * 10) == 20
        assert NONE.map_or_else(lambda: 0, lambda x: x * 10) == 0
        ```
    """

filter(predicate, *args, **kwargs)

Returns NONE if the option is NONE, otherwise calls predicate with the wrapped value.

This function works similar to PyoIterator::filter in the sense that we only keep the value if it matches a predicate.

You can imagine the Option[T] being an iterator over one or zero elements.

Parameters:

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

The predicate to apply to the contained value.

required
*args P.args

Additional positional arguments to pass to predicate.

()
**kwargs P.kwargs

Additional keyword arguments to pass to predicate.

{}

Returns:

Type Description
Option[T]

Option[T]: Some[T] if predicate returns true (where T is the wrapped value), NONE if predicate returns false.

Example
from pyochain import Some, NONE

def is_even(n: int) -> bool:
    return n % 2 == 0

assert NONE.filter(is_even).is_none()
assert Some(3).filter(is_even).is_none()
assert Some(4).filter(is_even) == Some(4)
Source code in pyochain/core/_option.pyi
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
def filter[**P](
    self,
    predicate: Callable[Concatenate[T, P], object],
    *args: P.args,
    **kwargs: P.kwargs,
) -> Option[T]:
    """Returns `NONE` if the option is `NONE`, otherwise calls predicate with the wrapped value.

    This function works similar to `PyoIterator::filter` in the sense that we only keep the value if it matches a predicate.

    You can imagine the `Option[T]` being an iterator over one or zero elements.

    Args:
        predicate (Callable[Concatenate[T, P], object]): The predicate to apply to the contained value.
        *args (P.args): Additional positional arguments to pass to predicate.
        **kwargs (P.kwargs): Additional keyword arguments to pass to predicate.

    Returns:
        Option[T]: `Some[T]` if predicate returns true (where T is the wrapped value), `NONE` if predicate returns false.


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

        def is_even(n: int) -> bool:
            return n % 2 == 0

        assert NONE.filter(is_even).is_none()
        assert Some(3).filter(is_even).is_none()
        assert Some(4).filter(is_even) == Some(4)
        ```
    """

iter()

Creates an Iterator over the optional value.

  • If the option is Some(value), the iterator yields value.
  • If the option is NONE, the iterator yields nothing.

Equivalent to Iter(self.unwrap()) if Some, or Iter() if NONE.

Returns:

Type Description
PyoIterator[T]

PyoIterator[T]: An Iterator over the optional value.

Example
from pyochain import Some, NONE, Iter

assert Some(42).iter().next() == Some(42)
assert NONE.iter().next().is_none()
assert Iter(42).next() == Some(42).iter().next()
Source code in pyochain/core/_option.pyi
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
def iter(self) -> PyoIterator[T]:
    """Creates an `Iterator` over the optional value.

    - If the option is `Some(value)`, the iterator yields `value`.
    - If the option is `NONE`, the iterator yields nothing.

    Equivalent to `Iter(self.unwrap())` if `Some`, or `Iter()` if `NONE`.

    Returns:
        PyoIterator[T]: An `Iterator` over the optional value.

    Example:
        ```python
        from pyochain import Some, NONE, Iter

        assert Some(42).iter().next() == Some(42)
        assert NONE.iter().next().is_none()
        assert Iter(42).next() == Some(42).iter().next()
        ```
    """

inspect(f, *args, **kwargs)

Applies a function to the contained Some value, returning the original Option.

This allows side effects (logging, debugging, metrics, etc.) on the wrapped value without changing it.

Parameters:

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

Function to apply to the Some value.

required
*args P.args

Additional positional arguments to pass to f.

()
**kwargs P.kwargs

Additional keyword arguments to pass to f.

{}

Returns:

Type Description
Option[T]

Option[T]: The original option, unchanged.

Example
from pyochain import Some, NONE, Vec

seen = Vec[int]([])

assert Some(2).inspect(lambda x: seen.append(x)) == Some(2)
assert seen == Vec(2)

assert NONE.inspect(lambda x: seen.append(x)).is_none()
assert seen == Vec(2)
Source code in pyochain/core/_option.pyi
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
def inspect[**P](
    self, f: Callable[Concatenate[T, P], object], *args: P.args, **kwargs: P.kwargs
) -> Option[T]:
    """Applies a function to the contained `Some` value, returning the original `Option`.

    This allows side effects (logging, debugging, metrics, etc.) on the wrapped value without changing it.

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

    Returns:
        Option[T]: The original option, unchanged.

    Example:
        ```python
        from pyochain import Some, NONE, Vec

        seen = Vec[int]([])

        assert Some(2).inspect(lambda x: seen.append(x)) == Some(2)
        assert seen == Vec(2)

        assert NONE.inspect(lambda x: seen.append(x)).is_none()
        assert seen == Vec(2)
        ```
    """

unzip()

Unzips an Option of a tuple into a tuple of Options.

If the option is Some((a, b)), this method returns (Some(a), Some(b)). If the option is NONE, it returns (NONE, NONE).

Returns:

Type Description
tuple[Option[S], Option[U]]

tuple[Option[S], Option[U]]: A tuple containing two options.

Example
from pyochain import Some, NONE

assert Some((1, "a")).unzip() == (Some(1), Some("a"))
assert NONE.unzip() == (NONE, NONE)
Source code in pyochain/core/_option.pyi
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
def unzip[S, U](self: Option[tuple[S, U]]) -> tuple[Option[S], Option[U]]:
    """Unzips an `Option` of a tuple into a tuple of `Option`s.

    If the option is `Some((a, b))`, this method returns `(Some(a), Some(b))`.
    If the option is `NONE`, it returns `(NONE, NONE)`.

    Returns:
        tuple[Option[S], Option[U]]: A tuple containing two options.

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

        assert Some((1, "a")).unzip() == (Some(1), Some("a"))
        assert NONE.unzip() == (NONE, NONE)
        ```
    """

zip(other)

Returns an Option[tuple[T, U]] containing a tuple of the values if both options are Some, otherwise returns NONE.

Parameters:

Name Type Description Default
other Option[U]

The other option to zip with.

required

Returns:

Type Description
Option[tuple[T, U]]

Option[tuple[T, U]]: Some((self, other)) if both are Some, otherwise NONE.

Example
from pyochain import Some, NONE

assert Some(1).zip(Some("a")) == Some((1, "a"))
assert Some(1).zip(NONE).is_none()
assert NONE.zip(Some("a")).is_none()
Source code in pyochain/core/_option.pyi
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
def zip[U](self, other: Option[U]) -> Option[tuple[T, U]]:
    """Returns an `Option[tuple[T, U]]` containing a tuple of the values if both options are `Some`, otherwise returns `NONE`.

    Args:
        other (Option[U]): The other option to zip with.

    Returns:
        Option[tuple[T, U]]: Some((self, other)) if both are Some, otherwise NONE.

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

        assert Some(1).zip(Some("a")) == Some((1, "a"))
        assert Some(1).zip(NONE).is_none()
        assert NONE.zip(Some("a")).is_none()
        ```
    """

zip_with(other, f)

Zips self and another Option with function f.

If self is Some(s) and other is Some(o), this method returns Some(f(s, o)).

Otherwise, NONE is returned.

Parameters:

Name Type Description Default
other Option[U]

The second option.

required
f Callable[[T, U], R]

The function to apply to the unwrapped values.

required

Returns:

Type Description
Option[R]

Option[R]: The resulting option after applying the function.

Example
from dataclasses import dataclass
from pyochain import Some, NONE

@dataclass
class Point:
    x: float
    y: float

x = Some(17.5)
y = Some(42.7)

assert x.zip_with(y, Point) == Some(Point(x=17.5, y=42.7))
assert x.zip_with(NONE, Point).is_none()
assert NONE.zip_with(y, Point).is_none()
Source code in pyochain/core/_option.pyi
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
def zip_with[U, R](self, other: Option[U], f: Callable[[T, U], R]) -> Option[R]:
    """Zips `self` and another `Option` with function `f`.

    If `self` is `Some(s)` and other is `Some(o)`, this method returns `Some(f(s, o))`.

    Otherwise, `NONE` is returned.

    Args:
        other (Option[U]): The second option.
        f (Callable[[T, U], R]): The function to apply to the unwrapped values.

    Returns:
        Option[R]: The resulting option after applying the function.

    Example:
        ```python
        from dataclasses import dataclass
        from pyochain import Some, NONE

        @dataclass
        class Point:
            x: float
            y: float

        x = Some(17.5)
        y = Some(42.7)

        assert x.zip_with(y, Point) == Some(Point(x=17.5, y=42.7))
        assert x.zip_with(NONE, Point).is_none()
        assert NONE.zip_with(y, Point).is_none()
        ```
    """

reduce(other, func)

Reduces two options into one, using the provided function if both are Some.

If self is Some(s) and other is Some(o), this method returns Some(func(s, o)).

Otherwise, if only one of self and other is Some, that value is returned.

If both self and other are NONE, NONE is returned.

Parameters:

Name Type Description Default
other Option[O]

The second option.

required
func Callable[[T, O], R]

The function to apply to the unwrapped values.

required

Returns:

Type Description
Option[R]

Option[R]: The resulting option after reduction.

Example
from pyochain import Some, NONE

s12 = Some(12)
s17 = Some(17)

def add(a: int, b: int) -> int:
    return a + b

assert s12.reduce(s17, add) == Some(29)
assert s12.reduce(NONE, add) == Some(12)
assert NONE.reduce(s17, add) == Some(17)
assert NONE.reduce(NONE, add).is_none()

def concat(a: str, b: str) -> str:
    return a + b

a = Some("Hello, ").reduce(Some("World!"), concat)
assert a == Some("Hello, World!")
b = Some("I am ").reduce(Some(26), lambda a, b: a + str(b))
assert b == Some("I am 26")
Source code in pyochain/core/_option.pyi
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
def reduce[O, R](self, other: Option[O], func: Callable[[T, O], R]) -> Option[R]:
    """Reduces two options into one, using the provided function if both are Some.

    If **self** is `Some(s)` and **other** is `Some(o)`, this method returns `Some(func(s, o))`.

    Otherwise, if only one of **self** and **other** is `Some`, that value is returned.

    If both **self** and **other** are `NONE`, `NONE` is returned.

    Args:
        other (Option[O]): The second option.
        func (Callable[[T, O], R]): The function to apply to the unwrapped values.

    Returns:
        Option[R]: The resulting option after reduction.

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

        s12 = Some(12)
        s17 = Some(17)

        def add(a: int, b: int) -> int:
            return a + b

        assert s12.reduce(s17, add) == Some(29)
        assert s12.reduce(NONE, add) == Some(12)
        assert NONE.reduce(s17, add) == Some(17)
        assert NONE.reduce(NONE, add).is_none()

        def concat(a: str, b: str) -> str:
            return a + b

        a = Some("Hello, ").reduce(Some("World!"), concat)
        assert a == Some("Hello, World!")
        b = Some("I am ").reduce(Some(26), lambda a, b: a + str(b))
        assert b == Some("I am 26")
        ```
    """

transpose()

Transposes an Option of a Result into a Result of an Option.

The mapping is as follows:

  • Some(Ok[T]) is mapped to Ok(Some[T])
  • Some(Err[E]) is mapped to Err[E]
  • NONE is mapped to Ok(NONE)

Returns:

Type Description
Result[Option[S], E]

Result[Option[S], E]: The transposed result.

Example
from pyochain import Some, Ok, Err, NONE

assert Some(Ok(5)).transpose().unwrap().unwrap() == 5
assert NONE.transpose().unwrap().is_none()
assert Some(Err("error")).transpose().unwrap_err() == "error"
Source code in pyochain/core/_option.pyi
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
def transpose[S, E](self: Option[Result[S, E]]) -> Result[Option[S], E]:
    """Transposes an `Option` of a `Result` into a `Result` of an `Option`.

    The mapping is as follows:

    - `Some(Ok[T])` is mapped to `Ok(Some[T])`
    - `Some(Err[E])` is mapped to `Err[E]`
    - `NONE` is mapped to `Ok(NONE)`

    Returns:
        Result[Option[S], E]: The transposed result.

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

        assert Some(Ok(5)).transpose().unwrap().unwrap() == 5
        assert NONE.transpose().unwrap().is_none()
        assert Some(Err("error")).transpose().unwrap_err() == "error"
        ```
    """

xor(optb)

Returns Some if exactly one of self, optb is Some, otherwise returns NONE.

Parameters:

Name Type Description Default
optb Option[object]

The other option to compare with.

required

Returns:

Type Description
Option[T]

Option[T]: Some value if exactly one option is Some, otherwise NONE.

Example
from pyochain import Some, NONE

assert Some(2).xor(NONE).unwrap() == 2
assert NONE.xor(Some(2)).unwrap() == 2
assert Some(2).xor(Some(2)).is_none()
assert NONE.xor(NONE).is_none()
assert Some("hello").xor(Some(1)).is_none()
Source code in pyochain/core/_option.pyi
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
def xor[O](self, optb: Option[object]) -> Option[T]:
    """Returns `Some` if exactly one of **self**, optb is `Some`, otherwise returns `NONE`.

    Args:
        optb (Option[object]): The other option to compare with.

    Returns:
        Option[T]: `Some` value if exactly one option is `Some`, otherwise `NONE`.

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

        assert Some(2).xor(NONE).unwrap() == 2
        assert NONE.xor(Some(2)).unwrap() == 2
        assert Some(2).xor(Some(2)).is_none()
        assert NONE.xor(NONE).is_none()
        assert Some("hello").xor(Some(1)).is_none()
        ```
    """

unwrap_or_none()

Returns the contained Some value or None.

This is a convenience method for interoperability with APIs that use None to represent the absence of a value,

e.g. when interacting with standard Python libraries, or external dependencies.

This is NOT the recommended use for handling Option in any code that can be controlled, as it defeats the purpose of using Option for explicit handling of optional values.

Returns:

Type Description
T | None

T | None: The contained Some value or None.

Example
from pyochain import Option, Some, NONE

assert NONE.unwrap_or_none() is None
assert Some(42).unwrap_or_none() == 42
Source code in pyochain/core/_option.pyi
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
def unwrap_or_none(self) -> T | None:
    """Returns the contained `Some` value or `None`.

    This is a convenience method for interoperability with APIs that use `None` to represent the absence of a value,

    e.g. when interacting with standard Python libraries, or external dependencies.

    This is **NOT** the recommended use for handling `Option` in any code that can be controlled, as it defeats the purpose of using `Option` for explicit handling of optional values.

    Returns:
        T | None: The contained `Some` value or `None`.

    Example:
        ```python
        from pyochain import Option, Some, NONE

        assert NONE.unwrap_or_none() is None
        assert Some(42).unwrap_or_none() == 42
        ```
    """