sain.result

Error handling with the Result type.

Result[T, E] is a convenient replacement for exceptions try/except

where Ok(T) is the successful value and Err(E) is the error result.

A function returning a Result may be defined like this:

from sain import Result, Ok, Err
from enum import Enum

class Version(Enum):
    VERSION_1 = 0x1
    VERSION_2 = 0x2

def parse_version(header: str) -> Result[Version, str]:
    match header.split('.')[0]:
        case '1':
            return Ok(Version.VERSION_1)
        case '2':
            return Ok(Version.VERSION_2)
        case _:
            return Err(f"Invalid version {header}")

simple pattern matching in Result is a straight-forward way to handle the returned value.

version = parse_version("1.2.0")
match version:
    Ok(v): print(f"working with version {v}")
    Err(e): print(f"error parsing header {e}")

In addition to working with pattern matching, Result provides a wide variety of different methods.

# `unwrap_or` is used to return a default value in case of an `Err` variant returned.
good_result: Result[str, bool] = Ok("Name")
print(username.unwrap_or("default_name"))  # name

bad_result: Result[str, bool] = Err(False)
print(username.unwrap_or("default_name"))  # name

If you're expecting a value should never be an Err at runtime, use .expect

def request(token: str) -> Result[bytes, None]:
    ...

response = request("token").expect("likely and invalid token")
# This will raise at runtime with the message 'likely ...'
  1# BSD 3-Clause License
  2#
  3# Copyright (c) 2022-Present, nxtlo
  4# All rights reserved.
  5#
  6# Redistribution and use in source and binary forms, with or without
  7# modification, are permitted provided that the following conditions are met:
  8#
  9# * Redistributions of source code must retain the above copyright notice, this
 10#   list of conditions and the following disclaimer.
 11#
 12# * Redistributions in binary form must reproduce the above copyright notice,
 13#   this list of conditions and the following disclaimer in the documentation
 14#   and/or other materials provided with the distribution.
 15#
 16# * Neither the name of the copyright holder nor the names of its
 17#   contributors may be used to endorse or promote products derived from
 18#   this software without specific prior written permission.
 19#
 20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 21# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 22# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 23# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 24# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 25# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 26# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 27# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 28# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 29# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 30"""Error handling with the `Result` type.
 31
 32`Result[T, E]` is a convenient replacement for exceptions `try/except`
 33
 34where `Ok(T)` is the successful value and `Err(E)` is the error result.
 35
 36A function returning a `Result` may be defined like this:
 37```py
 38from sain import Result, Ok, Err
 39from enum import Enum
 40
 41class Version(Enum):
 42    VERSION_1 = 0x1
 43    VERSION_2 = 0x2
 44
 45def parse_version(header: str) -> Result[Version, str]:
 46    match header.split('.')[0]:
 47        case '1':
 48            return Ok(Version.VERSION_1)
 49        case '2':
 50            return Ok(Version.VERSION_2)
 51        case _:
 52            return Err(f"Invalid version {header}")
 53```
 54
 55simple pattern matching in `Result` is a straight-forward way to handle the returned value.
 56
 57```py
 58version = parse_version("1.2.0")
 59match version:
 60    Ok(v): print(f"working with version {v}")
 61    Err(e): print(f"error parsing header {e}")
 62```
 63
 64In addition to working with pattern matching, `Result` provides a
 65wide variety of different methods.
 66
 67```py
 68# `unwrap_or` is used to return a default value in case of an `Err` variant returned.
 69good_result: Result[str, bool] = Ok("Name")
 70print(username.unwrap_or("default_name"))  # name
 71
 72bad_result: Result[str, bool] = Err(False)
 73print(username.unwrap_or("default_name"))  # name
 74```
 75
 76If you're expecting a value should never be an `Err` at runtime, use `.expect`
 77```py
 78def request(token: str) -> Result[bytes, None]:
 79    ...
 80
 81response = request("token").expect("likely and invalid token")
 82# This will raise at runtime with the message 'likely ...'
 83```
 84"""
 85
 86from __future__ import annotations
 87
 88__all__ = ("Ok", "Err", "Result")
 89
 90import dataclasses
 91import typing
 92
 93from sain import iter as _iter
 94from sain import option as _option
 95from sain.macros import rustc_diagnostic_item
 96
 97T = typing.TypeVar("T")
 98E = typing.TypeVar("E")
 99
100if typing.TYPE_CHECKING:
101    import collections.abc as collections
102
103    from typing_extensions import Never
104    from typing_extensions import Self
105    from typing_extensions import TypeAlias
106
107    from sain import Option
108
109    U = typing.TypeVar("U")
110    F = collections.Callable[[T], U]
111
112
113# Due to the nature of Python, Some methods here are repetitive to satisfy
114# ux and type checker, for an example `map` is only available for `Ok` but `Err` also needs to implement it
115# which simply just returns self, same way goes around for `map_err`.
116# Also for unwrapping values, `Err` guarantees an exception to be thrown but `Ok` doesn't.
117@rustc_diagnostic_item("Ok")
118@typing.final
119@dataclasses.dataclass(slots=True, frozen=True, repr=False)
120class Ok(typing.Generic[T]):
121    """Contains the success value of `Result[T, ...]`."""
122
123    _inner: T
124
125    ###############################
126    # * Querying operations. * #
127    ###############################
128
129    def is_ok(self) -> typing.Literal[True]:
130        """Returns `True` if the contained value is `Ok` and `False` if it an `Err`.
131
132        Example
133        -------
134        ```py
135        value: Result[str, None] = Ok("value")
136        assert value.is_ok() == True
137        ```
138        """
139        return True
140
141    def is_ok_and(self, f: F[T, bool]) -> bool:
142        """Returns `True` if the contained value is `Ok` and `f()` returns True.
143
144        Example
145        -------
146        ```py
147        value: Result[str, None] = Ok("value")
148        assert value.is_ok_and(lambda inner: inner == "value")
149        # True
150        ```
151        """
152        return f(self._inner)
153
154    # These are never truthy in an `Ok` instance.
155    def is_err(self) -> typing.Literal[False]:
156        """Returns `True` if the contained value is `Err`.
157
158        Example
159        -------
160        ```py
161        value: Result[str, None] = Ok("value")
162
163        assert value.is_err() == False
164        ```
165        """
166        return False
167
168    def is_err_and(self, f: F[T, bool]) -> typing.Literal[False]:
169        """Returns `True` if the contained value is `Ok` and `f()` returns True.
170
171        Example
172        -------
173        ```py
174        value: Result[str, None] = Ok("value")
175
176        assert value.is_err_and(lambda inner: inner == "value")
177        # False
178        ```
179        """
180        return False
181
182    ###################
183    # * Extractors * #
184    ###################
185
186    def expect(self, message: str, /) -> T:
187        """Return the underlying value if it was `Ok`, Raising `RuntimeError`
188        if it was `Err` with `message` passed to it.
189
190        Example
191        -------
192        ```py
193        ok: Result[str, None] = Ok("owo")
194        ok.expect("err") # owo
195
196        err: Result[str, None] = Err(None)
197        err.expect("err") # RuntimeError("err")
198        ```
199        """
200        return self._inner
201
202    def expect_err(self) -> Never:
203        """Return the `Err` value if `self` is an `Err`, panicking otherwise.
204
205        Example
206        -------
207        ```py
208        ok: Result[str, None] = Ok("owo")
209        ok.expect_err()  # RuntimeError("Called expect_err on `Ok`)
210
211        err: Result[str, None] = Err(None)
212        err.expect_err() # None
213        ```
214        """
215        raise RuntimeError("Called `expect_err` on an `Ok` value.")
216
217    def unwrap(self) -> T:
218        """Return the underlying value if it was `Ok`, Raising `RuntimeError` if it was `Err`.
219
220        Example
221        -------
222        ```py
223        ok: Result[str, None] = Ok("owo")
224        ok.unwrap() # owo
225
226        err: Result[str, None] = Err(None)
227        err.unwrap() # RuntimeError
228        ```
229        """
230        return self._inner
231
232    def unwrap_or(self, default: T, /) -> T:
233        """Return the underlying value if it was `Ok`, returning `default` if it was `Err`.
234
235        Example
236        -------
237        ```py
238        ok: Result[str, None] = Ok("OwO")
239        ok.unwrap_or("uwu") # OwO
240
241        err: Result[str, None] = Err(None)
242        err.unwrap_or("uwu") # uwu
243        ```
244        """
245        return self._inner
246
247    def unwrap_or_else(self, f: F[E, T]) -> T:
248        """Return the contained `Ok` value or computes it from `f()` if it was `Err`.
249
250        Example
251        -------
252        ```py
253        ok: Result[int, str] = Ok(4)
254        ok.unwrap_or_else(lambda e: 0) # 4
255
256        err: Result[int, str] = Err("word")
257        err.unwrap_or_else(lambda e: len(e)) # 4
258        ```
259        """
260        return self._inner
261
262    def unwrap_err(self) -> Never:
263        """Return the contained `Err` value, Raising if it was `Ok`.
264
265        Example
266        -------
267        ```py
268        ok: Result[str, None] = Ok("buh")
269        ok.unwrap_err()  # RuntimeError
270
271        err: Result[str, None] = Err(None)
272        err.unwrap_err() == None
273        # True
274        ```
275        """
276        raise RuntimeError(f"Called `unwrap_err` on an `Ok` variant: {self._inner!r}")
277
278    ############################
279    # * Conversion adapters. * #
280    ############################
281
282    def ok(self) -> Option[T]:
283        """Transform `Result[T, E]` to `Option[T]`, mapping `Ok(v)` to `Some(T)` and `Err(e)` to `None`.
284
285        Example
286        -------
287        ```py
288        value: Result[str, None] = Ok("buh")
289        value.ok().is_some() # True
290
291        value: Result[str, int] = Err(0)
292        value.ok().is_none() # True
293        ```
294        """
295        return _option.Some(self._inner)
296
297    def err(self) -> Option[T]:
298        """Transform `Result[T, E]` to `Option[E]`, mapping `Ok(v)` to `None` and `Err(e)` to `Some(e)`.
299
300        Example
301        -------
302        ```py
303        value: Result[str, None] = Ok("buh")
304        value.err().is_none() # True
305
306        value: Result[str, int] = Err(0)
307        value.err().is_some() # True
308        ```
309        """
310        return _option.NOTHING
311
312    def inspect(self, f: F[T, typing.Any]) -> Self:
313        """Call a function to the contained value if it was `Ok` and do nothing if it was `Err`
314
315        Example
316        -------
317        ```py
318        def sink(value: str) -> None:
319            # do something with value
320            print("Called " + value)
321
322        x: Result[str, None] = Ok("ok")
323        x.inspect(sink) # "Called ok"
324
325        x: Result[str, str] = Err("err")
326        x.inspect(sink) # None
327        ```
328        """
329        f(self._inner)
330        return self
331
332    def inspect_err(self, f: F[E, typing.Any]) -> Self:
333        """Call a function to the contained value if it was `Err` and do nothing if it was `Ok`
334
335        Example
336        -------
337        ```py
338        def sink(value: str) -> None:
339            # do something with value
340            print("Called " + value)
341
342        x: Result[str, None] = Ok("ok")
343        x.inspect_err(sink) # None
344
345        x: Result[str, str] = Err("err")
346        x.inspect_err(sink) # Called err
347        ```
348        """
349        return self
350
351    def map(self, f: F[T, U], /) -> Ok[U]:
352        """Map `Result<T, E>` to `Result<U, E>` by applying a function to the `Ok` value,
353        leaving `Err` untouched.
354
355        Example
356        -------
357        ```py
358        ok: Result[str, int] = Ok("1")
359        ok.map(lambda c: int(c) + 1) # Ok(2)
360
361        err: Result[str, int] = Err(0)
362        err.map(str.upper) # Err(0)
363        ```
364        """
365        return Ok(f(self._inner))
366
367    def map_or(self, f: F[T, U], default: U, /) -> U:
368        """Returns the provided `default` if the contained value is `Err`,
369
370        Otherwise extracts the `Ok` value and maps it to `f()`
371
372        Example
373        -------
374        ```py
375        x: Result[str, str] = Ok("foo")
376        assert x.map_or(lambda c: len(c), 42) == 3
377
378        x: Result[str, str] = Err("bar")
379        assert x.map_or(lambda c: len(c), 42) == 42
380        ```
381        """
382        return f(self._inner)
383
384    def map_or_else(self, f: F[T, U], default: F[E, U], /) -> U:
385        """Maps a Result<T, E> to U by applying fallback function `default` to a contained Err value,
386        or function `f` to a contained Ok value.
387
388        Example
389        -------
390        ```py
391        x: Result[str, str] = Ok("four")
392        assert x.map_or_else(
393            lambda ok: 2 * len(ok),
394            default=lambda err: len(err)
395        ) == 8
396
397        x: Result[str, str] = Err("bar")
398        assert x.map_or_else(
399            lambda c: 2 * len(c),
400            lambda err: len(err)
401        ) == 3
402        ```
403        """
404        return f(self._inner)
405
406    def map_err(self, f: F[E, U], /) -> Self:
407        """Maps a `Result[T, E]` to `Result[T, U]` by applying function `f`, leaving the `Ok` value untouched.
408
409        Example
410        -------
411        ```py
412        x: Result[str, int] = Ok("blue")
413        x.map_err(lambda err: err + 1) # Ok("blue")
414
415        x: Result[str, int] = Err(5)
416        x.map_err(float) # Err(5.0)
417        ```
418        """
419        return self
420
421    ##############################
422    # * Iterator constructors. * #
423    ##############################
424
425    def iter(self) -> _iter.ExactSizeIterator[T]:
426        """An iterator over the possible contained value.
427
428        If `self` was `Ok`, then the iterator will yield the Ok `T`. otherwise yields nothing.
429
430        Example
431        -------
432        ```py
433        c: Result[str, int] = Ok("blue")
434        c.iter().next() == Some("blue")
435
436        c: Result[str, int] = Err(0)
437        c.iter().next() == Some(None)
438        ```
439        """
440        return _iter.Once(self._inner)
441
442    def __iter__(self) -> collections.Iterator[T]:
443        yield self._inner
444
445    #################
446    # * Overloads * #
447    #################
448
449    def __repr__(self) -> str:
450        return f"Ok({self._inner!r})"
451
452    def __or__(self, other: T) -> T:
453        return self._inner
454
455    def __invert__(self) -> T:
456        return self._inner
457
458
459@rustc_diagnostic_item("Err")
460@typing.final
461@dataclasses.dataclass(slots=True, frozen=True, repr=False)
462class Err(typing.Generic[E]):
463    """Contains the error value of `Result[..., E]`."""
464
465    _inner: E
466
467    ################################
468    # * Boolean operations. * #
469    ################################
470
471    def is_ok(self) -> typing.Literal[False]:
472        """Returns `True` if the contained value is `Ok` and `False` if it an `Err`.
473
474        Example
475        -------
476        ```py
477        value: Result[str, None] = Err(None)
478
479        assert value.is_ok() == False
480        ```
481        """
482        return False
483
484    def is_ok_and(self, f: F[E, bool]) -> typing.Literal[False]:
485        """Returns `True` if the contained value is `Ok` and `f()` returns True.
486
487        Example
488        -------
489        ```py
490        value: Result[str, None] = Err(None)
491
492        assert value.is_ok_and(lambda inner: inner == "value")
493        # False
494        ```
495        """
496        return False
497
498    # These are never truthy in an `Ok` instance.
499    def is_err(self) -> typing.Literal[True]:
500        """Returns `True` if the contained value is `Err`.
501
502        Example
503        -------
504        ```py
505        value: Result[str, None] = Err(None)
506
507        assert value.is_err() == True
508        ```
509        """
510        return True
511
512    def is_err_and(self, f: F[E, bool]) -> bool:
513        """Returns `True` if the contained value is `Ok` and `f()` returns True..
514
515        Example
516        -------
517        ```py
518        value: Result[str, None] = Err(None)
519
520        assert value.is_err_and(lambda err: err is None)
521        # True
522        ```
523        """
524        return f(self._inner)
525
526    ###################
527    # * Extractors. * #
528    ###################
529
530    def expect(self, msg: str) -> Never:
531        """Return the underlying value if it was `Ok`, Raising `RuntimeError`
532        if it was `Err` with `message` passed to it.
533
534        Example
535        -------
536        ```py
537        ok: Result[str, None] = Ok("owo")
538        ok.expect("err") # owo
539
540        err: Result[str, None] = Err(None)
541        err.expect("err") # RuntimeError("err")
542        ```
543        """
544        raise RuntimeError(msg) from None
545
546    def expect_err(self) -> E:
547        """Return the `Err` if it was `Err`, panicking otherwise.
548
549
550        Example
551        -------
552        ```py
553        x: Result[str, None] = Ok("owo")
554        x.expect_err()  # RuntimeError("Called expect_err on `Ok`)
555
556        x: Result[str, None] = Err(None)
557        x.expect_err() # None
558        ```
559        """
560        return self._inner
561
562    def unwrap(self) -> Never:
563        """Return the underlying value if it was `Ok`, Raising `RuntimeError` if it was `Err`.
564
565        Example
566        -------
567        ```py
568        ok: Result[str, None] = Ok("owo")
569        ok.unwrap() # owo
570
571        err: Result[str, None] = Err(None)
572        err.unwrap() # RuntimeError
573        ```
574        """
575        raise RuntimeError(
576            f"Called `unwrap()` on an `Err` variant: {self._inner!r}"
577        ) from None
578
579    def unwrap_or(self, default: T, /) -> T:
580        """Return the underlying value if it was `Ok`, returning `default` if it was `Err`.
581
582        Example
583        -------
584        ```py
585        ok: Result[str, None] = Ok("OwO")
586        ok.unwrap_or("uwu") # OwO
587
588        err: Result[str, None] = Err(None)
589        err.unwrap_or("uwu") # uwu
590        ```
591        """
592        return default
593
594    def unwrap_or_else(self, f: F[E, T]) -> T:
595        """Return the contained `Ok` value or computes it from `f()` if it was `Err`.
596
597        Example
598        -------
599        ```py
600        ok: Result[int, str] = Ok(4)
601        ok.unwrap_or_else(lambda e: 0) # 4
602
603        err: Result[int, str] = Err("word")
604        err.unwrap_or_else(lambda e: len(e)) # 4
605        ```
606        """
607        return f(self._inner)
608
609    def unwrap_err(self) -> E:
610        """Return the contained `Err` value, Raising if it was `Ok`.
611
612        Example
613        -------
614        ```py
615        ok: Result[str, None] = Ok("buh")
616        ok.unwrap_err()  # RuntimeError
617
618        err: Result[str, None] = Err(None)
619        err.unwrap_err() == None
620        # True
621        ```
622        """
623        return self._inner
624
625    ############################
626    # * Conversion adapters. * #
627    ############################
628
629    def inspect(self, f: F[T, typing.Any]) -> Self:
630        """Call a function to the contained value if it was `Ok` and do nothing if it was `Err`
631
632        Example
633        -------
634        ```py
635        def sink(value: str) -> None:
636            # do something with value
637            print("Called " + value)
638
639        x: Result[str, None] = Ok("ok")
640        x.inspect(sink) # "Called ok"
641
642        x: Result[str, str] = Err("err")
643        x.inspect(sink) # None
644        ```
645        """
646        return self
647
648    def inspect_err(self, f: F[E, typing.Any]) -> Self:
649        """Call a function to the contained value if it was `Err` and do nothing if it was `Ok`
650
651        Example
652        -------
653        ```py
654        def sink(value: str) -> None:
655            # do something with value
656            print("Called " + value)
657
658        x: Result[str, None] = Ok("ok")
659        x.inspect_err(sink) # None
660
661        x: Result[str, str] = Err("err")
662        x.inspect_err(sink) # Called err
663        ```
664        """
665        f(self._inner)
666        return self
667
668    def ok(self) -> Option[None]:
669        """Transform `Result[T, E]` to `Option[T]`, mapping `Ok(v)` to `Some(T)` and `Err(e)` to `None`.
670
671        Example
672        -------
673        ```py
674        value: Result[str, None] = Ok("buh")
675        value.ok().is_some() # True
676
677        value: Result[str, int] = Err(0)
678        value.ok().is_none() # True
679        ```
680        """
681        return _option.NOTHING
682
683    def err(self) -> Option[E]:
684        """Transform `Result[T, E]` to `Option[E]`, mapping `Ok(v)` to `None` and `Err(e)` to `Some(e)`.
685
686        Example
687        -------
688        ```py
689        value: Result[str, None] = Ok("buh")
690        value.err().is_none() # True
691
692        value: Result[str, int] = Err(0)
693        value.err().is_some() # True
694        ```
695        """
696        return _option.Some(self._inner)
697
698    def map(self, f: F[E, U]) -> Self:
699        """Map `Result<T, E>` to `Result<U, E>` by applying a function to the `Ok` value,
700        leaving `Err` untouched.
701
702        Example
703        -------
704        ```py
705        ok: Result[str, int] = Ok("1")
706        ok.map(lambda c: int(c) + 1) # Ok(2)
707
708        err: Result[str, int] = Err(0)
709        err.map(str.upper) # Err(0)
710        ```
711        """
712        return self
713
714    def map_or(self, f: F[E, U], default: U, /) -> U:
715        """Returns the provided `default` if the contained value is `Err`,
716
717        Otherwise extracts the `Ok` value and maps it to `f()`
718
719        Example
720        -------
721        ```py
722        x: Result[str, str] = Ok("foo")
723        assert x.map_or(lambda c: len(c), 42) == 3
724
725        x: Result[str, str] = Err("bar")
726        assert x.map_or(lambda c: len(c), 42) == 42
727        ```
728        """
729        return default
730
731    def map_or_else(self, f: F[T, U], default: F[E, U], /) -> U:
732        """Maps a Result<T, E> to U by applying fallback function `default` to a contained Err value,
733        or function `f` to a contained Ok value.
734
735        Example
736        -------
737        ```py
738        x: Result[str, str] = Ok("four")
739        assert x.map_or_else(
740            lambda ok: 2 * len(ok),
741            default=lambda err: len(err)
742        ) == 8
743
744        x: Result[str, str] = Err("bar")
745        assert x.map_or_else(
746            lambda c: 2 * len(c),
747            lambda err: len(err)
748        ) == 3
749        ```
750        """
751        return default(self._inner)
752
753    def map_err(self, f: F[E, U]) -> Err[U]:
754        """Maps a `Result[T, E]` to `Result[T, U]` by applying function `f`, leaving the `Ok` value untouched.
755
756        Example
757        -------
758        ```py
759        x: Result[str, int] = Ok("blue")
760        x.map_err(lambda err: err + 1) # Ok("blue")
761
762        x: Result[str, int] = Err(5)
763        x.map_err(float) # Err(5.0)
764        ```
765        """
766        return Err(f(self._inner))
767
768    ##############################
769    # * Iterator constructors. * #
770    ##############################
771
772    def iter(self) -> _iter.ExactSizeIterator[E]:
773        """An iterator over the possible contained value.
774
775        If `self` was `Ok`, then the iterator will yield `T`, otherwise yields nothing.
776
777        Example
778        -------
779        ```py
780        c: Result[str, int] = Ok("blue")
781        c.iter().next() == Some("blue")
782
783        c: Result[str, int] = Err(0)
784        c.iter().next() == Some(None)
785        ```
786        """
787        return _iter.Empty()
788
789    def __iter__(self) -> collections.Iterator[E]:
790        yield from ()
791
792    #################
793    # * Overloads * #
794    #################
795
796    def __repr__(self) -> str:
797        return f"Err({self._inner!r})"
798
799    def __or__(self, other: T) -> T:
800        return other
801
802    def __invert__(self) -> Never:
803        self.unwrap()
804
805
806Result: TypeAlias = "Ok[T] | Err[E]"
807"""A type hint for a function that may return `Ok[T]` or `Err[E]`,
808
809See the module documentation level for more information."""
@rustc_diagnostic_item('Ok')
@typing.final
@dataclasses.dataclass(slots=True, frozen=True, repr=False)
class Ok(typing.Generic[~T]):
118@rustc_diagnostic_item("Ok")
119@typing.final
120@dataclasses.dataclass(slots=True, frozen=True, repr=False)
121class Ok(typing.Generic[T]):
122    """Contains the success value of `Result[T, ...]`."""
123
124    _inner: T
125
126    ###############################
127    # * Querying operations. * #
128    ###############################
129
130    def is_ok(self) -> typing.Literal[True]:
131        """Returns `True` if the contained value is `Ok` and `False` if it an `Err`.
132
133        Example
134        -------
135        ```py
136        value: Result[str, None] = Ok("value")
137        assert value.is_ok() == True
138        ```
139        """
140        return True
141
142    def is_ok_and(self, f: F[T, bool]) -> bool:
143        """Returns `True` if the contained value is `Ok` and `f()` returns True.
144
145        Example
146        -------
147        ```py
148        value: Result[str, None] = Ok("value")
149        assert value.is_ok_and(lambda inner: inner == "value")
150        # True
151        ```
152        """
153        return f(self._inner)
154
155    # These are never truthy in an `Ok` instance.
156    def is_err(self) -> typing.Literal[False]:
157        """Returns `True` if the contained value is `Err`.
158
159        Example
160        -------
161        ```py
162        value: Result[str, None] = Ok("value")
163
164        assert value.is_err() == False
165        ```
166        """
167        return False
168
169    def is_err_and(self, f: F[T, bool]) -> typing.Literal[False]:
170        """Returns `True` if the contained value is `Ok` and `f()` returns True.
171
172        Example
173        -------
174        ```py
175        value: Result[str, None] = Ok("value")
176
177        assert value.is_err_and(lambda inner: inner == "value")
178        # False
179        ```
180        """
181        return False
182
183    ###################
184    # * Extractors * #
185    ###################
186
187    def expect(self, message: str, /) -> T:
188        """Return the underlying value if it was `Ok`, Raising `RuntimeError`
189        if it was `Err` with `message` passed to it.
190
191        Example
192        -------
193        ```py
194        ok: Result[str, None] = Ok("owo")
195        ok.expect("err") # owo
196
197        err: Result[str, None] = Err(None)
198        err.expect("err") # RuntimeError("err")
199        ```
200        """
201        return self._inner
202
203    def expect_err(self) -> Never:
204        """Return the `Err` value if `self` is an `Err`, panicking otherwise.
205
206        Example
207        -------
208        ```py
209        ok: Result[str, None] = Ok("owo")
210        ok.expect_err()  # RuntimeError("Called expect_err on `Ok`)
211
212        err: Result[str, None] = Err(None)
213        err.expect_err() # None
214        ```
215        """
216        raise RuntimeError("Called `expect_err` on an `Ok` value.")
217
218    def unwrap(self) -> T:
219        """Return the underlying value if it was `Ok`, Raising `RuntimeError` if it was `Err`.
220
221        Example
222        -------
223        ```py
224        ok: Result[str, None] = Ok("owo")
225        ok.unwrap() # owo
226
227        err: Result[str, None] = Err(None)
228        err.unwrap() # RuntimeError
229        ```
230        """
231        return self._inner
232
233    def unwrap_or(self, default: T, /) -> T:
234        """Return the underlying value if it was `Ok`, returning `default` if it was `Err`.
235
236        Example
237        -------
238        ```py
239        ok: Result[str, None] = Ok("OwO")
240        ok.unwrap_or("uwu") # OwO
241
242        err: Result[str, None] = Err(None)
243        err.unwrap_or("uwu") # uwu
244        ```
245        """
246        return self._inner
247
248    def unwrap_or_else(self, f: F[E, T]) -> T:
249        """Return the contained `Ok` value or computes it from `f()` if it was `Err`.
250
251        Example
252        -------
253        ```py
254        ok: Result[int, str] = Ok(4)
255        ok.unwrap_or_else(lambda e: 0) # 4
256
257        err: Result[int, str] = Err("word")
258        err.unwrap_or_else(lambda e: len(e)) # 4
259        ```
260        """
261        return self._inner
262
263    def unwrap_err(self) -> Never:
264        """Return the contained `Err` value, Raising if it was `Ok`.
265
266        Example
267        -------
268        ```py
269        ok: Result[str, None] = Ok("buh")
270        ok.unwrap_err()  # RuntimeError
271
272        err: Result[str, None] = Err(None)
273        err.unwrap_err() == None
274        # True
275        ```
276        """
277        raise RuntimeError(f"Called `unwrap_err` on an `Ok` variant: {self._inner!r}")
278
279    ############################
280    # * Conversion adapters. * #
281    ############################
282
283    def ok(self) -> Option[T]:
284        """Transform `Result[T, E]` to `Option[T]`, mapping `Ok(v)` to `Some(T)` and `Err(e)` to `None`.
285
286        Example
287        -------
288        ```py
289        value: Result[str, None] = Ok("buh")
290        value.ok().is_some() # True
291
292        value: Result[str, int] = Err(0)
293        value.ok().is_none() # True
294        ```
295        """
296        return _option.Some(self._inner)
297
298    def err(self) -> Option[T]:
299        """Transform `Result[T, E]` to `Option[E]`, mapping `Ok(v)` to `None` and `Err(e)` to `Some(e)`.
300
301        Example
302        -------
303        ```py
304        value: Result[str, None] = Ok("buh")
305        value.err().is_none() # True
306
307        value: Result[str, int] = Err(0)
308        value.err().is_some() # True
309        ```
310        """
311        return _option.NOTHING
312
313    def inspect(self, f: F[T, typing.Any]) -> Self:
314        """Call a function to the contained value if it was `Ok` and do nothing if it was `Err`
315
316        Example
317        -------
318        ```py
319        def sink(value: str) -> None:
320            # do something with value
321            print("Called " + value)
322
323        x: Result[str, None] = Ok("ok")
324        x.inspect(sink) # "Called ok"
325
326        x: Result[str, str] = Err("err")
327        x.inspect(sink) # None
328        ```
329        """
330        f(self._inner)
331        return self
332
333    def inspect_err(self, f: F[E, typing.Any]) -> Self:
334        """Call a function to the contained value if it was `Err` and do nothing if it was `Ok`
335
336        Example
337        -------
338        ```py
339        def sink(value: str) -> None:
340            # do something with value
341            print("Called " + value)
342
343        x: Result[str, None] = Ok("ok")
344        x.inspect_err(sink) # None
345
346        x: Result[str, str] = Err("err")
347        x.inspect_err(sink) # Called err
348        ```
349        """
350        return self
351
352    def map(self, f: F[T, U], /) -> Ok[U]:
353        """Map `Result<T, E>` to `Result<U, E>` by applying a function to the `Ok` value,
354        leaving `Err` untouched.
355
356        Example
357        -------
358        ```py
359        ok: Result[str, int] = Ok("1")
360        ok.map(lambda c: int(c) + 1) # Ok(2)
361
362        err: Result[str, int] = Err(0)
363        err.map(str.upper) # Err(0)
364        ```
365        """
366        return Ok(f(self._inner))
367
368    def map_or(self, f: F[T, U], default: U, /) -> U:
369        """Returns the provided `default` if the contained value is `Err`,
370
371        Otherwise extracts the `Ok` value and maps it to `f()`
372
373        Example
374        -------
375        ```py
376        x: Result[str, str] = Ok("foo")
377        assert x.map_or(lambda c: len(c), 42) == 3
378
379        x: Result[str, str] = Err("bar")
380        assert x.map_or(lambda c: len(c), 42) == 42
381        ```
382        """
383        return f(self._inner)
384
385    def map_or_else(self, f: F[T, U], default: F[E, U], /) -> U:
386        """Maps a Result<T, E> to U by applying fallback function `default` to a contained Err value,
387        or function `f` to a contained Ok value.
388
389        Example
390        -------
391        ```py
392        x: Result[str, str] = Ok("four")
393        assert x.map_or_else(
394            lambda ok: 2 * len(ok),
395            default=lambda err: len(err)
396        ) == 8
397
398        x: Result[str, str] = Err("bar")
399        assert x.map_or_else(
400            lambda c: 2 * len(c),
401            lambda err: len(err)
402        ) == 3
403        ```
404        """
405        return f(self._inner)
406
407    def map_err(self, f: F[E, U], /) -> Self:
408        """Maps a `Result[T, E]` to `Result[T, U]` by applying function `f`, leaving the `Ok` value untouched.
409
410        Example
411        -------
412        ```py
413        x: Result[str, int] = Ok("blue")
414        x.map_err(lambda err: err + 1) # Ok("blue")
415
416        x: Result[str, int] = Err(5)
417        x.map_err(float) # Err(5.0)
418        ```
419        """
420        return self
421
422    ##############################
423    # * Iterator constructors. * #
424    ##############################
425
426    def iter(self) -> _iter.ExactSizeIterator[T]:
427        """An iterator over the possible contained value.
428
429        If `self` was `Ok`, then the iterator will yield the Ok `T`. otherwise yields nothing.
430
431        Example
432        -------
433        ```py
434        c: Result[str, int] = Ok("blue")
435        c.iter().next() == Some("blue")
436
437        c: Result[str, int] = Err(0)
438        c.iter().next() == Some(None)
439        ```
440        """
441        return _iter.Once(self._inner)
442
443    def __iter__(self) -> collections.Iterator[T]:
444        yield self._inner
445
446    #################
447    # * Overloads * #
448    #################
449
450    def __repr__(self) -> str:
451        return f"Ok({self._inner!r})"
452
453    def __or__(self, other: T) -> T:
454        return self._inner
455
456    def __invert__(self) -> T:
457        return self._inner

Contains the success value of Result[T, ...].

Implementations

This class implements .Result.html#variant.Ok">Ok in Rust.

Ok(_inner: ~T)
def is_ok(self) -> Literal[True]:
130    def is_ok(self) -> typing.Literal[True]:
131        """Returns `True` if the contained value is `Ok` and `False` if it an `Err`.
132
133        Example
134        -------
135        ```py
136        value: Result[str, None] = Ok("value")
137        assert value.is_ok() == True
138        ```
139        """
140        return True

Returns True if the contained value is Ok and False if it an Err.

Example
value: Result[str, None] = Ok("value")
assert value.is_ok() == True
def is_ok_and(self, f: Callable[[~T], bool]) -> bool:
142    def is_ok_and(self, f: F[T, bool]) -> bool:
143        """Returns `True` if the contained value is `Ok` and `f()` returns True.
144
145        Example
146        -------
147        ```py
148        value: Result[str, None] = Ok("value")
149        assert value.is_ok_and(lambda inner: inner == "value")
150        # True
151        ```
152        """
153        return f(self._inner)

Returns True if the contained value is Ok and f() returns True.

Example
value: Result[str, None] = Ok("value")
assert value.is_ok_and(lambda inner: inner == "value")
# True
def is_err(self) -> Literal[False]:
156    def is_err(self) -> typing.Literal[False]:
157        """Returns `True` if the contained value is `Err`.
158
159        Example
160        -------
161        ```py
162        value: Result[str, None] = Ok("value")
163
164        assert value.is_err() == False
165        ```
166        """
167        return False

Returns True if the contained value is Err.

Example
value: Result[str, None] = Ok("value")

assert value.is_err() == False
def is_err_and(self, f: Callable[[~T], bool]) -> Literal[False]:
169    def is_err_and(self, f: F[T, bool]) -> typing.Literal[False]:
170        """Returns `True` if the contained value is `Ok` and `f()` returns True.
171
172        Example
173        -------
174        ```py
175        value: Result[str, None] = Ok("value")
176
177        assert value.is_err_and(lambda inner: inner == "value")
178        # False
179        ```
180        """
181        return False

Returns True if the contained value is Ok and f() returns True.

Example
value: Result[str, None] = Ok("value")

assert value.is_err_and(lambda inner: inner == "value")
# False
def expect(self, message: str, /) -> ~T:
187    def expect(self, message: str, /) -> T:
188        """Return the underlying value if it was `Ok`, Raising `RuntimeError`
189        if it was `Err` with `message` passed to it.
190
191        Example
192        -------
193        ```py
194        ok: Result[str, None] = Ok("owo")
195        ok.expect("err") # owo
196
197        err: Result[str, None] = Err(None)
198        err.expect("err") # RuntimeError("err")
199        ```
200        """
201        return self._inner

Return the underlying value if it was Ok, Raising RuntimeError if it was Err with message passed to it.

Example
ok: Result[str, None] = Ok("owo")
ok.expect("err") # owo

err: Result[str, None] = Err(None)
err.expect("err") # RuntimeError("err")
def expect_err(self) -> Never:
203    def expect_err(self) -> Never:
204        """Return the `Err` value if `self` is an `Err`, panicking otherwise.
205
206        Example
207        -------
208        ```py
209        ok: Result[str, None] = Ok("owo")
210        ok.expect_err()  # RuntimeError("Called expect_err on `Ok`)
211
212        err: Result[str, None] = Err(None)
213        err.expect_err() # None
214        ```
215        """
216        raise RuntimeError("Called `expect_err` on an `Ok` value.")

Return the Err value if self is an Err, panicking otherwise.

Example
ok: Result[str, None] = Ok("owo")
ok.expect_err()  # RuntimeError("Called expect_err on `Ok`)

err: Result[str, None] = Err(None)
err.expect_err() # None
def unwrap(self) -> ~T:
218    def unwrap(self) -> T:
219        """Return the underlying value if it was `Ok`, Raising `RuntimeError` if it was `Err`.
220
221        Example
222        -------
223        ```py
224        ok: Result[str, None] = Ok("owo")
225        ok.unwrap() # owo
226
227        err: Result[str, None] = Err(None)
228        err.unwrap() # RuntimeError
229        ```
230        """
231        return self._inner

Return the underlying value if it was Ok, Raising RuntimeError if it was Err.

Example
ok: Result[str, None] = Ok("owo")
ok.unwrap() # owo

err: Result[str, None] = Err(None)
err.unwrap() # RuntimeError
def unwrap_or(self, default: ~T, /) -> ~T:
233    def unwrap_or(self, default: T, /) -> T:
234        """Return the underlying value if it was `Ok`, returning `default` if it was `Err`.
235
236        Example
237        -------
238        ```py
239        ok: Result[str, None] = Ok("OwO")
240        ok.unwrap_or("uwu") # OwO
241
242        err: Result[str, None] = Err(None)
243        err.unwrap_or("uwu") # uwu
244        ```
245        """
246        return self._inner

Return the underlying value if it was Ok, returning default if it was Err.

Example
ok: Result[str, None] = Ok("OwO")
ok.unwrap_or("uwu") # OwO

err: Result[str, None] = Err(None)
err.unwrap_or("uwu") # uwu
def unwrap_or_else(self, f: Callable[[~E], ~T]) -> ~T:
248    def unwrap_or_else(self, f: F[E, T]) -> T:
249        """Return the contained `Ok` value or computes it from `f()` if it was `Err`.
250
251        Example
252        -------
253        ```py
254        ok: Result[int, str] = Ok(4)
255        ok.unwrap_or_else(lambda e: 0) # 4
256
257        err: Result[int, str] = Err("word")
258        err.unwrap_or_else(lambda e: len(e)) # 4
259        ```
260        """
261        return self._inner

Return the contained Ok value or computes it from f() if it was Err.

Example
ok: Result[int, str] = Ok(4)
ok.unwrap_or_else(lambda e: 0) # 4

err: Result[int, str] = Err("word")
err.unwrap_or_else(lambda e: len(e)) # 4
def unwrap_err(self) -> Never:
263    def unwrap_err(self) -> Never:
264        """Return the contained `Err` value, Raising if it was `Ok`.
265
266        Example
267        -------
268        ```py
269        ok: Result[str, None] = Ok("buh")
270        ok.unwrap_err()  # RuntimeError
271
272        err: Result[str, None] = Err(None)
273        err.unwrap_err() == None
274        # True
275        ```
276        """
277        raise RuntimeError(f"Called `unwrap_err` on an `Ok` variant: {self._inner!r}")

Return the contained Err value, Raising if it was Ok.

Example
ok: Result[str, None] = Ok("buh")
ok.unwrap_err()  # RuntimeError

err: Result[str, None] = Err(None)
err.unwrap_err() == None
# True
def ok(self) -> 'Option[T]':
283    def ok(self) -> Option[T]:
284        """Transform `Result[T, E]` to `Option[T]`, mapping `Ok(v)` to `Some(T)` and `Err(e)` to `None`.
285
286        Example
287        -------
288        ```py
289        value: Result[str, None] = Ok("buh")
290        value.ok().is_some() # True
291
292        value: Result[str, int] = Err(0)
293        value.ok().is_none() # True
294        ```
295        """
296        return _option.Some(self._inner)

Transform Result[T, E] to Option[T], mapping Ok(v) to Some(T) and Err(e) to None.

Example
value: Result[str, None] = Ok("buh")
value.ok().is_some() # True

value: Result[str, int] = Err(0)
value.ok().is_none() # True
def err(self) -> 'Option[T]':
298    def err(self) -> Option[T]:
299        """Transform `Result[T, E]` to `Option[E]`, mapping `Ok(v)` to `None` and `Err(e)` to `Some(e)`.
300
301        Example
302        -------
303        ```py
304        value: Result[str, None] = Ok("buh")
305        value.err().is_none() # True
306
307        value: Result[str, int] = Err(0)
308        value.err().is_some() # True
309        ```
310        """
311        return _option.NOTHING

Transform Result[T, E] to Option[E], mapping Ok(v) to None and Err(e) to Some(e).

Example
value: Result[str, None] = Ok("buh")
value.err().is_none() # True

value: Result[str, int] = Err(0)
value.err().is_some() # True
def inspect(self, f: Callable[[~T], typing.Any]) -> Self:
313    def inspect(self, f: F[T, typing.Any]) -> Self:
314        """Call a function to the contained value if it was `Ok` and do nothing if it was `Err`
315
316        Example
317        -------
318        ```py
319        def sink(value: str) -> None:
320            # do something with value
321            print("Called " + value)
322
323        x: Result[str, None] = Ok("ok")
324        x.inspect(sink) # "Called ok"
325
326        x: Result[str, str] = Err("err")
327        x.inspect(sink) # None
328        ```
329        """
330        f(self._inner)
331        return self

Call a function to the contained value if it was Ok and do nothing if it was Err

Example
def sink(value: str) -> None:
    # do something with value
    print("Called " + value)

x: Result[str, None] = Ok("ok")
x.inspect(sink) # "Called ok"

x: Result[str, str] = Err("err")
x.inspect(sink) # None
def inspect_err(self, f: Callable[[~E], typing.Any]) -> Self:
333    def inspect_err(self, f: F[E, typing.Any]) -> Self:
334        """Call a function to the contained value if it was `Err` and do nothing if it was `Ok`
335
336        Example
337        -------
338        ```py
339        def sink(value: str) -> None:
340            # do something with value
341            print("Called " + value)
342
343        x: Result[str, None] = Ok("ok")
344        x.inspect_err(sink) # None
345
346        x: Result[str, str] = Err("err")
347        x.inspect_err(sink) # Called err
348        ```
349        """
350        return self

Call a function to the contained value if it was Err and do nothing if it was Ok

Example
def sink(value: str) -> None:
    # do something with value
    print("Called " + value)

x: Result[str, None] = Ok("ok")
x.inspect_err(sink) # None

x: Result[str, str] = Err("err")
x.inspect_err(sink) # Called err
def map(self, f: Callable[[~T], ~U], /) -> Ok[~U]:
352    def map(self, f: F[T, U], /) -> Ok[U]:
353        """Map `Result<T, E>` to `Result<U, E>` by applying a function to the `Ok` value,
354        leaving `Err` untouched.
355
356        Example
357        -------
358        ```py
359        ok: Result[str, int] = Ok("1")
360        ok.map(lambda c: int(c) + 1) # Ok(2)
361
362        err: Result[str, int] = Err(0)
363        err.map(str.upper) # Err(0)
364        ```
365        """
366        return Ok(f(self._inner))

Map Result<T, E> to Result<U, E> by applying a function to the Ok value, leaving Err untouched.

Example
ok: Result[str, int] = Ok("1")
ok.map(lambda c: int(c) + 1) # Ok(2)

err: Result[str, int] = Err(0)
err.map(str.upper) # Err(0)
def map_or(self, f: Callable[[~T], ~U], default: ~U, /) -> ~U:
368    def map_or(self, f: F[T, U], default: U, /) -> U:
369        """Returns the provided `default` if the contained value is `Err`,
370
371        Otherwise extracts the `Ok` value and maps it to `f()`
372
373        Example
374        -------
375        ```py
376        x: Result[str, str] = Ok("foo")
377        assert x.map_or(lambda c: len(c), 42) == 3
378
379        x: Result[str, str] = Err("bar")
380        assert x.map_or(lambda c: len(c), 42) == 42
381        ```
382        """
383        return f(self._inner)

Returns the provided default if the contained value is Err,

Otherwise extracts the Ok value and maps it to f()

Example
x: Result[str, str] = Ok("foo")
assert x.map_or(lambda c: len(c), 42) == 3

x: Result[str, str] = Err("bar")
assert x.map_or(lambda c: len(c), 42) == 42
def map_or_else(self, f: Callable[[~T], ~U], default: Callable[[~E], ~U], /) -> ~U:
385    def map_or_else(self, f: F[T, U], default: F[E, U], /) -> U:
386        """Maps a Result<T, E> to U by applying fallback function `default` to a contained Err value,
387        or function `f` to a contained Ok value.
388
389        Example
390        -------
391        ```py
392        x: Result[str, str] = Ok("four")
393        assert x.map_or_else(
394            lambda ok: 2 * len(ok),
395            default=lambda err: len(err)
396        ) == 8
397
398        x: Result[str, str] = Err("bar")
399        assert x.map_or_else(
400            lambda c: 2 * len(c),
401            lambda err: len(err)
402        ) == 3
403        ```
404        """
405        return f(self._inner)

Maps a Result to U by applying fallback function default to a contained Err value, or function f to a contained Ok value.

Example
x: Result[str, str] = Ok("four")
assert x.map_or_else(
    lambda ok: 2 * len(ok),
    default=lambda err: len(err)
) == 8

x: Result[str, str] = Err("bar")
assert x.map_or_else(
    lambda c: 2 * len(c),
    lambda err: len(err)
) == 3
def map_err(self, f: Callable[[~E], ~U], /) -> Self:
407    def map_err(self, f: F[E, U], /) -> Self:
408        """Maps a `Result[T, E]` to `Result[T, U]` by applying function `f`, leaving the `Ok` value untouched.
409
410        Example
411        -------
412        ```py
413        x: Result[str, int] = Ok("blue")
414        x.map_err(lambda err: err + 1) # Ok("blue")
415
416        x: Result[str, int] = Err(5)
417        x.map_err(float) # Err(5.0)
418        ```
419        """
420        return self

Maps a Result[T, E] to Result[T, U] by applying function f, leaving the Ok value untouched.

Example
x: Result[str, int] = Ok("blue")
x.map_err(lambda err: err + 1) # Ok("blue")

x: Result[str, int] = Err(5)
x.map_err(float) # Err(5.0)
def iter(self) -> sain.iter.ExactSizeIterator[~T]:
426    def iter(self) -> _iter.ExactSizeIterator[T]:
427        """An iterator over the possible contained value.
428
429        If `self` was `Ok`, then the iterator will yield the Ok `T`. otherwise yields nothing.
430
431        Example
432        -------
433        ```py
434        c: Result[str, int] = Ok("blue")
435        c.iter().next() == Some("blue")
436
437        c: Result[str, int] = Err(0)
438        c.iter().next() == Some(None)
439        ```
440        """
441        return _iter.Once(self._inner)

An iterator over the possible contained value.

If self was Ok, then the iterator will yield the Ok T. otherwise yields nothing.

Example
c: Result[str, int] = Ok("blue")
c.iter().next() == Some("blue")

c: Result[str, int] = Err(0)
c.iter().next() == Some(None)
@rustc_diagnostic_item('Err')
@typing.final
@dataclasses.dataclass(slots=True, frozen=True, repr=False)
class Err(typing.Generic[~E]):
460@rustc_diagnostic_item("Err")
461@typing.final
462@dataclasses.dataclass(slots=True, frozen=True, repr=False)
463class Err(typing.Generic[E]):
464    """Contains the error value of `Result[..., E]`."""
465
466    _inner: E
467
468    ################################
469    # * Boolean operations. * #
470    ################################
471
472    def is_ok(self) -> typing.Literal[False]:
473        """Returns `True` if the contained value is `Ok` and `False` if it an `Err`.
474
475        Example
476        -------
477        ```py
478        value: Result[str, None] = Err(None)
479
480        assert value.is_ok() == False
481        ```
482        """
483        return False
484
485    def is_ok_and(self, f: F[E, bool]) -> typing.Literal[False]:
486        """Returns `True` if the contained value is `Ok` and `f()` returns True.
487
488        Example
489        -------
490        ```py
491        value: Result[str, None] = Err(None)
492
493        assert value.is_ok_and(lambda inner: inner == "value")
494        # False
495        ```
496        """
497        return False
498
499    # These are never truthy in an `Ok` instance.
500    def is_err(self) -> typing.Literal[True]:
501        """Returns `True` if the contained value is `Err`.
502
503        Example
504        -------
505        ```py
506        value: Result[str, None] = Err(None)
507
508        assert value.is_err() == True
509        ```
510        """
511        return True
512
513    def is_err_and(self, f: F[E, bool]) -> bool:
514        """Returns `True` if the contained value is `Ok` and `f()` returns True..
515
516        Example
517        -------
518        ```py
519        value: Result[str, None] = Err(None)
520
521        assert value.is_err_and(lambda err: err is None)
522        # True
523        ```
524        """
525        return f(self._inner)
526
527    ###################
528    # * Extractors. * #
529    ###################
530
531    def expect(self, msg: str) -> Never:
532        """Return the underlying value if it was `Ok`, Raising `RuntimeError`
533        if it was `Err` with `message` passed to it.
534
535        Example
536        -------
537        ```py
538        ok: Result[str, None] = Ok("owo")
539        ok.expect("err") # owo
540
541        err: Result[str, None] = Err(None)
542        err.expect("err") # RuntimeError("err")
543        ```
544        """
545        raise RuntimeError(msg) from None
546
547    def expect_err(self) -> E:
548        """Return the `Err` if it was `Err`, panicking otherwise.
549
550
551        Example
552        -------
553        ```py
554        x: Result[str, None] = Ok("owo")
555        x.expect_err()  # RuntimeError("Called expect_err on `Ok`)
556
557        x: Result[str, None] = Err(None)
558        x.expect_err() # None
559        ```
560        """
561        return self._inner
562
563    def unwrap(self) -> Never:
564        """Return the underlying value if it was `Ok`, Raising `RuntimeError` if it was `Err`.
565
566        Example
567        -------
568        ```py
569        ok: Result[str, None] = Ok("owo")
570        ok.unwrap() # owo
571
572        err: Result[str, None] = Err(None)
573        err.unwrap() # RuntimeError
574        ```
575        """
576        raise RuntimeError(
577            f"Called `unwrap()` on an `Err` variant: {self._inner!r}"
578        ) from None
579
580    def unwrap_or(self, default: T, /) -> T:
581        """Return the underlying value if it was `Ok`, returning `default` if it was `Err`.
582
583        Example
584        -------
585        ```py
586        ok: Result[str, None] = Ok("OwO")
587        ok.unwrap_or("uwu") # OwO
588
589        err: Result[str, None] = Err(None)
590        err.unwrap_or("uwu") # uwu
591        ```
592        """
593        return default
594
595    def unwrap_or_else(self, f: F[E, T]) -> T:
596        """Return the contained `Ok` value or computes it from `f()` if it was `Err`.
597
598        Example
599        -------
600        ```py
601        ok: Result[int, str] = Ok(4)
602        ok.unwrap_or_else(lambda e: 0) # 4
603
604        err: Result[int, str] = Err("word")
605        err.unwrap_or_else(lambda e: len(e)) # 4
606        ```
607        """
608        return f(self._inner)
609
610    def unwrap_err(self) -> E:
611        """Return the contained `Err` value, Raising if it was `Ok`.
612
613        Example
614        -------
615        ```py
616        ok: Result[str, None] = Ok("buh")
617        ok.unwrap_err()  # RuntimeError
618
619        err: Result[str, None] = Err(None)
620        err.unwrap_err() == None
621        # True
622        ```
623        """
624        return self._inner
625
626    ############################
627    # * Conversion adapters. * #
628    ############################
629
630    def inspect(self, f: F[T, typing.Any]) -> Self:
631        """Call a function to the contained value if it was `Ok` and do nothing if it was `Err`
632
633        Example
634        -------
635        ```py
636        def sink(value: str) -> None:
637            # do something with value
638            print("Called " + value)
639
640        x: Result[str, None] = Ok("ok")
641        x.inspect(sink) # "Called ok"
642
643        x: Result[str, str] = Err("err")
644        x.inspect(sink) # None
645        ```
646        """
647        return self
648
649    def inspect_err(self, f: F[E, typing.Any]) -> Self:
650        """Call a function to the contained value if it was `Err` and do nothing if it was `Ok`
651
652        Example
653        -------
654        ```py
655        def sink(value: str) -> None:
656            # do something with value
657            print("Called " + value)
658
659        x: Result[str, None] = Ok("ok")
660        x.inspect_err(sink) # None
661
662        x: Result[str, str] = Err("err")
663        x.inspect_err(sink) # Called err
664        ```
665        """
666        f(self._inner)
667        return self
668
669    def ok(self) -> Option[None]:
670        """Transform `Result[T, E]` to `Option[T]`, mapping `Ok(v)` to `Some(T)` and `Err(e)` to `None`.
671
672        Example
673        -------
674        ```py
675        value: Result[str, None] = Ok("buh")
676        value.ok().is_some() # True
677
678        value: Result[str, int] = Err(0)
679        value.ok().is_none() # True
680        ```
681        """
682        return _option.NOTHING
683
684    def err(self) -> Option[E]:
685        """Transform `Result[T, E]` to `Option[E]`, mapping `Ok(v)` to `None` and `Err(e)` to `Some(e)`.
686
687        Example
688        -------
689        ```py
690        value: Result[str, None] = Ok("buh")
691        value.err().is_none() # True
692
693        value: Result[str, int] = Err(0)
694        value.err().is_some() # True
695        ```
696        """
697        return _option.Some(self._inner)
698
699    def map(self, f: F[E, U]) -> Self:
700        """Map `Result<T, E>` to `Result<U, E>` by applying a function to the `Ok` value,
701        leaving `Err` untouched.
702
703        Example
704        -------
705        ```py
706        ok: Result[str, int] = Ok("1")
707        ok.map(lambda c: int(c) + 1) # Ok(2)
708
709        err: Result[str, int] = Err(0)
710        err.map(str.upper) # Err(0)
711        ```
712        """
713        return self
714
715    def map_or(self, f: F[E, U], default: U, /) -> U:
716        """Returns the provided `default` if the contained value is `Err`,
717
718        Otherwise extracts the `Ok` value and maps it to `f()`
719
720        Example
721        -------
722        ```py
723        x: Result[str, str] = Ok("foo")
724        assert x.map_or(lambda c: len(c), 42) == 3
725
726        x: Result[str, str] = Err("bar")
727        assert x.map_or(lambda c: len(c), 42) == 42
728        ```
729        """
730        return default
731
732    def map_or_else(self, f: F[T, U], default: F[E, U], /) -> U:
733        """Maps a Result<T, E> to U by applying fallback function `default` to a contained Err value,
734        or function `f` to a contained Ok value.
735
736        Example
737        -------
738        ```py
739        x: Result[str, str] = Ok("four")
740        assert x.map_or_else(
741            lambda ok: 2 * len(ok),
742            default=lambda err: len(err)
743        ) == 8
744
745        x: Result[str, str] = Err("bar")
746        assert x.map_or_else(
747            lambda c: 2 * len(c),
748            lambda err: len(err)
749        ) == 3
750        ```
751        """
752        return default(self._inner)
753
754    def map_err(self, f: F[E, U]) -> Err[U]:
755        """Maps a `Result[T, E]` to `Result[T, U]` by applying function `f`, leaving the `Ok` value untouched.
756
757        Example
758        -------
759        ```py
760        x: Result[str, int] = Ok("blue")
761        x.map_err(lambda err: err + 1) # Ok("blue")
762
763        x: Result[str, int] = Err(5)
764        x.map_err(float) # Err(5.0)
765        ```
766        """
767        return Err(f(self._inner))
768
769    ##############################
770    # * Iterator constructors. * #
771    ##############################
772
773    def iter(self) -> _iter.ExactSizeIterator[E]:
774        """An iterator over the possible contained value.
775
776        If `self` was `Ok`, then the iterator will yield `T`, otherwise yields nothing.
777
778        Example
779        -------
780        ```py
781        c: Result[str, int] = Ok("blue")
782        c.iter().next() == Some("blue")
783
784        c: Result[str, int] = Err(0)
785        c.iter().next() == Some(None)
786        ```
787        """
788        return _iter.Empty()
789
790    def __iter__(self) -> collections.Iterator[E]:
791        yield from ()
792
793    #################
794    # * Overloads * #
795    #################
796
797    def __repr__(self) -> str:
798        return f"Err({self._inner!r})"
799
800    def __or__(self, other: T) -> T:
801        return other
802
803    def __invert__(self) -> Never:
804        self.unwrap()

Contains the error value of Result[..., E].

Implementations

This class implements .Result.html#variant.Err">Err in Rust.

Err(_inner: ~E)
def is_ok(self) -> Literal[False]:
472    def is_ok(self) -> typing.Literal[False]:
473        """Returns `True` if the contained value is `Ok` and `False` if it an `Err`.
474
475        Example
476        -------
477        ```py
478        value: Result[str, None] = Err(None)
479
480        assert value.is_ok() == False
481        ```
482        """
483        return False

Returns True if the contained value is Ok and False if it an Err.

Example
value: Result[str, None] = Err(None)

assert value.is_ok() == False
def is_ok_and(self, f: Callable[[~E], bool]) -> Literal[False]:
485    def is_ok_and(self, f: F[E, bool]) -> typing.Literal[False]:
486        """Returns `True` if the contained value is `Ok` and `f()` returns True.
487
488        Example
489        -------
490        ```py
491        value: Result[str, None] = Err(None)
492
493        assert value.is_ok_and(lambda inner: inner == "value")
494        # False
495        ```
496        """
497        return False

Returns True if the contained value is Ok and f() returns True.

Example
value: Result[str, None] = Err(None)

assert value.is_ok_and(lambda inner: inner == "value")
# False
def is_err(self) -> Literal[True]:
500    def is_err(self) -> typing.Literal[True]:
501        """Returns `True` if the contained value is `Err`.
502
503        Example
504        -------
505        ```py
506        value: Result[str, None] = Err(None)
507
508        assert value.is_err() == True
509        ```
510        """
511        return True

Returns True if the contained value is Err.

Example
value: Result[str, None] = Err(None)

assert value.is_err() == True
def is_err_and(self, f: Callable[[~E], bool]) -> bool:
513    def is_err_and(self, f: F[E, bool]) -> bool:
514        """Returns `True` if the contained value is `Ok` and `f()` returns True..
515
516        Example
517        -------
518        ```py
519        value: Result[str, None] = Err(None)
520
521        assert value.is_err_and(lambda err: err is None)
522        # True
523        ```
524        """
525        return f(self._inner)

Returns True if the contained value is Ok and f() returns True..

Example
value: Result[str, None] = Err(None)

assert value.is_err_and(lambda err: err is None)
# True
def expect(self, msg: str) -> Never:
531    def expect(self, msg: str) -> Never:
532        """Return the underlying value if it was `Ok`, Raising `RuntimeError`
533        if it was `Err` with `message` passed to it.
534
535        Example
536        -------
537        ```py
538        ok: Result[str, None] = Ok("owo")
539        ok.expect("err") # owo
540
541        err: Result[str, None] = Err(None)
542        err.expect("err") # RuntimeError("err")
543        ```
544        """
545        raise RuntimeError(msg) from None

Return the underlying value if it was Ok, Raising RuntimeError if it was Err with message passed to it.

Example
ok: Result[str, None] = Ok("owo")
ok.expect("err") # owo

err: Result[str, None] = Err(None)
err.expect("err") # RuntimeError("err")
def expect_err(self) -> ~E:
547    def expect_err(self) -> E:
548        """Return the `Err` if it was `Err`, panicking otherwise.
549
550
551        Example
552        -------
553        ```py
554        x: Result[str, None] = Ok("owo")
555        x.expect_err()  # RuntimeError("Called expect_err on `Ok`)
556
557        x: Result[str, None] = Err(None)
558        x.expect_err() # None
559        ```
560        """
561        return self._inner

Return the Err if it was Err, panicking otherwise.

Example
x: Result[str, None] = Ok("owo")
x.expect_err()  # RuntimeError("Called expect_err on `Ok`)

x: Result[str, None] = Err(None)
x.expect_err() # None
def unwrap(self) -> Never:
563    def unwrap(self) -> Never:
564        """Return the underlying value if it was `Ok`, Raising `RuntimeError` if it was `Err`.
565
566        Example
567        -------
568        ```py
569        ok: Result[str, None] = Ok("owo")
570        ok.unwrap() # owo
571
572        err: Result[str, None] = Err(None)
573        err.unwrap() # RuntimeError
574        ```
575        """
576        raise RuntimeError(
577            f"Called `unwrap()` on an `Err` variant: {self._inner!r}"
578        ) from None

Return the underlying value if it was Ok, Raising RuntimeError if it was Err.

Example
ok: Result[str, None] = Ok("owo")
ok.unwrap() # owo

err: Result[str, None] = Err(None)
err.unwrap() # RuntimeError
def unwrap_or(self, default: ~T, /) -> ~T:
580    def unwrap_or(self, default: T, /) -> T:
581        """Return the underlying value if it was `Ok`, returning `default` if it was `Err`.
582
583        Example
584        -------
585        ```py
586        ok: Result[str, None] = Ok("OwO")
587        ok.unwrap_or("uwu") # OwO
588
589        err: Result[str, None] = Err(None)
590        err.unwrap_or("uwu") # uwu
591        ```
592        """
593        return default

Return the underlying value if it was Ok, returning default if it was Err.

Example
ok: Result[str, None] = Ok("OwO")
ok.unwrap_or("uwu") # OwO

err: Result[str, None] = Err(None)
err.unwrap_or("uwu") # uwu
def unwrap_or_else(self, f: Callable[[~E], ~T]) -> ~T:
595    def unwrap_or_else(self, f: F[E, T]) -> T:
596        """Return the contained `Ok` value or computes it from `f()` if it was `Err`.
597
598        Example
599        -------
600        ```py
601        ok: Result[int, str] = Ok(4)
602        ok.unwrap_or_else(lambda e: 0) # 4
603
604        err: Result[int, str] = Err("word")
605        err.unwrap_or_else(lambda e: len(e)) # 4
606        ```
607        """
608        return f(self._inner)

Return the contained Ok value or computes it from f() if it was Err.

Example
ok: Result[int, str] = Ok(4)
ok.unwrap_or_else(lambda e: 0) # 4

err: Result[int, str] = Err("word")
err.unwrap_or_else(lambda e: len(e)) # 4
def unwrap_err(self) -> ~E:
610    def unwrap_err(self) -> E:
611        """Return the contained `Err` value, Raising if it was `Ok`.
612
613        Example
614        -------
615        ```py
616        ok: Result[str, None] = Ok("buh")
617        ok.unwrap_err()  # RuntimeError
618
619        err: Result[str, None] = Err(None)
620        err.unwrap_err() == None
621        # True
622        ```
623        """
624        return self._inner

Return the contained Err value, Raising if it was Ok.

Example
ok: Result[str, None] = Ok("buh")
ok.unwrap_err()  # RuntimeError

err: Result[str, None] = Err(None)
err.unwrap_err() == None
# True
def inspect(self, f: Callable[[~T], typing.Any]) -> Self:
630    def inspect(self, f: F[T, typing.Any]) -> Self:
631        """Call a function to the contained value if it was `Ok` and do nothing if it was `Err`
632
633        Example
634        -------
635        ```py
636        def sink(value: str) -> None:
637            # do something with value
638            print("Called " + value)
639
640        x: Result[str, None] = Ok("ok")
641        x.inspect(sink) # "Called ok"
642
643        x: Result[str, str] = Err("err")
644        x.inspect(sink) # None
645        ```
646        """
647        return self

Call a function to the contained value if it was Ok and do nothing if it was Err

Example
def sink(value: str) -> None:
    # do something with value
    print("Called " + value)

x: Result[str, None] = Ok("ok")
x.inspect(sink) # "Called ok"

x: Result[str, str] = Err("err")
x.inspect(sink) # None
def inspect_err(self, f: Callable[[~E], typing.Any]) -> Self:
649    def inspect_err(self, f: F[E, typing.Any]) -> Self:
650        """Call a function to the contained value if it was `Err` and do nothing if it was `Ok`
651
652        Example
653        -------
654        ```py
655        def sink(value: str) -> None:
656            # do something with value
657            print("Called " + value)
658
659        x: Result[str, None] = Ok("ok")
660        x.inspect_err(sink) # None
661
662        x: Result[str, str] = Err("err")
663        x.inspect_err(sink) # Called err
664        ```
665        """
666        f(self._inner)
667        return self

Call a function to the contained value if it was Err and do nothing if it was Ok

Example
def sink(value: str) -> None:
    # do something with value
    print("Called " + value)

x: Result[str, None] = Ok("ok")
x.inspect_err(sink) # None

x: Result[str, str] = Err("err")
x.inspect_err(sink) # Called err
def ok(self) -> 'Option[None]':
669    def ok(self) -> Option[None]:
670        """Transform `Result[T, E]` to `Option[T]`, mapping `Ok(v)` to `Some(T)` and `Err(e)` to `None`.
671
672        Example
673        -------
674        ```py
675        value: Result[str, None] = Ok("buh")
676        value.ok().is_some() # True
677
678        value: Result[str, int] = Err(0)
679        value.ok().is_none() # True
680        ```
681        """
682        return _option.NOTHING

Transform Result[T, E] to Option[T], mapping Ok(v) to Some(T) and Err(e) to None.

Example
value: Result[str, None] = Ok("buh")
value.ok().is_some() # True

value: Result[str, int] = Err(0)
value.ok().is_none() # True
def err(self) -> 'Option[E]':
684    def err(self) -> Option[E]:
685        """Transform `Result[T, E]` to `Option[E]`, mapping `Ok(v)` to `None` and `Err(e)` to `Some(e)`.
686
687        Example
688        -------
689        ```py
690        value: Result[str, None] = Ok("buh")
691        value.err().is_none() # True
692
693        value: Result[str, int] = Err(0)
694        value.err().is_some() # True
695        ```
696        """
697        return _option.Some(self._inner)

Transform Result[T, E] to Option[E], mapping Ok(v) to None and Err(e) to Some(e).

Example
value: Result[str, None] = Ok("buh")
value.err().is_none() # True

value: Result[str, int] = Err(0)
value.err().is_some() # True
def map(self, f: Callable[[~E], ~U]) -> Self:
699    def map(self, f: F[E, U]) -> Self:
700        """Map `Result<T, E>` to `Result<U, E>` by applying a function to the `Ok` value,
701        leaving `Err` untouched.
702
703        Example
704        -------
705        ```py
706        ok: Result[str, int] = Ok("1")
707        ok.map(lambda c: int(c) + 1) # Ok(2)
708
709        err: Result[str, int] = Err(0)
710        err.map(str.upper) # Err(0)
711        ```
712        """
713        return self

Map Result<T, E> to Result<U, E> by applying a function to the Ok value, leaving Err untouched.

Example
ok: Result[str, int] = Ok("1")
ok.map(lambda c: int(c) + 1) # Ok(2)

err: Result[str, int] = Err(0)
err.map(str.upper) # Err(0)
def map_or(self, f: Callable[[~E], ~U], default: ~U, /) -> ~U:
715    def map_or(self, f: F[E, U], default: U, /) -> U:
716        """Returns the provided `default` if the contained value is `Err`,
717
718        Otherwise extracts the `Ok` value and maps it to `f()`
719
720        Example
721        -------
722        ```py
723        x: Result[str, str] = Ok("foo")
724        assert x.map_or(lambda c: len(c), 42) == 3
725
726        x: Result[str, str] = Err("bar")
727        assert x.map_or(lambda c: len(c), 42) == 42
728        ```
729        """
730        return default

Returns the provided default if the contained value is Err,

Otherwise extracts the Ok value and maps it to f()

Example
x: Result[str, str] = Ok("foo")
assert x.map_or(lambda c: len(c), 42) == 3

x: Result[str, str] = Err("bar")
assert x.map_or(lambda c: len(c), 42) == 42
def map_or_else(self, f: Callable[[~T], ~U], default: Callable[[~E], ~U], /) -> ~U:
732    def map_or_else(self, f: F[T, U], default: F[E, U], /) -> U:
733        """Maps a Result<T, E> to U by applying fallback function `default` to a contained Err value,
734        or function `f` to a contained Ok value.
735
736        Example
737        -------
738        ```py
739        x: Result[str, str] = Ok("four")
740        assert x.map_or_else(
741            lambda ok: 2 * len(ok),
742            default=lambda err: len(err)
743        ) == 8
744
745        x: Result[str, str] = Err("bar")
746        assert x.map_or_else(
747            lambda c: 2 * len(c),
748            lambda err: len(err)
749        ) == 3
750        ```
751        """
752        return default(self._inner)

Maps a Result to U by applying fallback function default to a contained Err value, or function f to a contained Ok value.

Example
x: Result[str, str] = Ok("four")
assert x.map_or_else(
    lambda ok: 2 * len(ok),
    default=lambda err: len(err)
) == 8

x: Result[str, str] = Err("bar")
assert x.map_or_else(
    lambda c: 2 * len(c),
    lambda err: len(err)
) == 3
def map_err(self, f: Callable[[~E], ~U]) -> Err[~U]:
754    def map_err(self, f: F[E, U]) -> Err[U]:
755        """Maps a `Result[T, E]` to `Result[T, U]` by applying function `f`, leaving the `Ok` value untouched.
756
757        Example
758        -------
759        ```py
760        x: Result[str, int] = Ok("blue")
761        x.map_err(lambda err: err + 1) # Ok("blue")
762
763        x: Result[str, int] = Err(5)
764        x.map_err(float) # Err(5.0)
765        ```
766        """
767        return Err(f(self._inner))

Maps a Result[T, E] to Result[T, U] by applying function f, leaving the Ok value untouched.

Example
x: Result[str, int] = Ok("blue")
x.map_err(lambda err: err + 1) # Ok("blue")

x: Result[str, int] = Err(5)
x.map_err(float) # Err(5.0)
def iter(self) -> sain.iter.ExactSizeIterator[~E]:
773    def iter(self) -> _iter.ExactSizeIterator[E]:
774        """An iterator over the possible contained value.
775
776        If `self` was `Ok`, then the iterator will yield `T`, otherwise yields nothing.
777
778        Example
779        -------
780        ```py
781        c: Result[str, int] = Ok("blue")
782        c.iter().next() == Some("blue")
783
784        c: Result[str, int] = Err(0)
785        c.iter().next() == Some(None)
786        ```
787        """
788        return _iter.Empty()

An iterator over the possible contained value.

If self was Ok, then the iterator will yield T, otherwise yields nothing.

Example
c: Result[str, int] = Ok("blue")
c.iter().next() == Some("blue")

c: Result[str, int] = Err(0)
c.iter().next() == Some(None)
Result: TypeAlias = 'Ok[T] | Err[E]'

A type hint for a function that may return Ok[T] or Err[E],

See the module documentation level for more information.