Source code for stdlibx.option.methods.result

 1from __future__ import annotations
 2
 3from typing import TYPE_CHECKING, Callable, TypeVar
 4
 5from stdlibx import result
 6from stdlibx.option._option import is_some, nothing, some
 7
 8if TYPE_CHECKING:
 9    from stdlibx.option.types import Option
10    from stdlibx.result.types import Result
11
12T = TypeVar("T")
13U = TypeVar("U")
14E = TypeVar("E")
15
16
[docs] 17def ok_or(opt: Option[T], error: E) -> Result[T, E]: 18 if is_some(opt): 19 return result.ok(opt.value) 20 return result.error(error)
21 22
[docs] 23def ok_or_else(opt: Option[T], error: Callable[[], E]) -> Result[T, E]: 24 if is_some(opt): 25 return result.ok(opt.value) 26 return result.error(error())
27 28
[docs] 29def transpose(opt: Option[Result[U, E]]) -> Result[Option[U], E]: 30 if is_some(opt) and result.is_ok(opt.value): 31 return result.ok(some(opt.value.value)) 32 elif is_some(opt) and result.is_err(opt.value): 33 return result.error(opt.value.error) 34 else: 35 return result.ok(nothing())