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