Source code for stdlibx.option._option

 1from __future__ import annotations
 2
 3from functools import wraps
 4from typing import TYPE_CHECKING, Callable, Generic, TypeVar
 5
 6from stdlibx.option.types import Nothing, Some
 7from typing_extensions import ParamSpec, TypeIs
 8
 9if TYPE_CHECKING:
10    from stdlibx.option.types import Operation, Option
11
12
13T = TypeVar("T")
14E = TypeVar("E")
15U = TypeVar("U")
16P = ParamSpec("P")
17
18
[docs] 19def some(value: T) -> Option[T]: 20 return _Some(value)
21 22
[docs] 23def nothing() -> Option[T]: 24 return _Nothing()
25 26
[docs] 27def is_some(opt: Option[T]) -> TypeIs[Some[T]]: 28 return opt.is_some()
29 30
[docs] 31def is_none(opt: Option[T]) -> TypeIs[Nothing]: 32 return opt.is_none()
33 34
[docs] 35def maybe(func: Callable[P, T | None], *args: P.args, **kwargs: P.kwargs) -> Option[T]: 36 value = func(*args, **kwargs) 37 if value is None: 38 return nothing() 39 return some(value)
40 41
[docs] 42def optional(func: Callable[P, T | None]) -> Callable[P, Option[T]]: 43 @wraps(func) 44 def _wrapped(*args: P.args, **kwargs: P.kwargs) -> Option[T]: 45 result = func(*args, **kwargs) 46 if result is None: 47 return nothing() 48 return some(result) 49 50 return _wrapped
51 52 53class _Some(Generic[T]): 54 __match_args__ = ("value",) 55 __slots__ = ("value",) 56 57 value: T 58 59 def __init__(self, value: T) -> None: 60 self.value = value 61 62 def __repr__(self) -> str: 63 return f"Some({self.value!r})" 64 65 def __eq__(self, other: object) -> bool: 66 if isinstance(other, Some): 67 return other.value == self.value 68 return False 69 70 def is_some(self): 71 return True 72 73 def is_none(self): 74 return False 75 76 def apply(self, operation: Operation[Option[T], U]) -> U: 77 return operation(self) 78 79 80class _Nothing: 81 __slots__ = () 82 83 def __repr__(self) -> str: 84 return "Nothing()" 85 86 def __eq__(self, other: object) -> bool: 87 return isinstance(other, Nothing) 88 89 def is_some(self): 90 return False 91 92 def is_none(self): 93 return True 94 95 def apply(self, operation: Operation[Option[T], U]) -> U: 96 return operation(self)