-
Notifications
You must be signed in to change notification settings - Fork 0
Option
Handling optional values with the Option type.
Option[T] is a type that represents an optional value: either it contains a value of type T (Some), or it contains no value (None). It is a safe alternative to using None directly, providing a rich set of methods to work with the presence or absence of a value.
Method overview
In addition to working with pattern matching (via is_some / is_none), Option provides a wide variety of different methods.
-
somereturns an Option containing the given value (Somevariant) -
nonereturns an Option representing no value (Nonevariant)
The is_some and is_none methods return True if the Option is Some or None, respectively.
is_some_and additionally checks a predicate on the contained value when the option is Some.
Extracting contained values
These methods extract the contained value in an Option[T] when it is the Some variant. If the Option is None:
-
expectpanics with a provided custom message -
unwrappanics with a generic message -
unwrap_orreturns the provided default value -
unwrap_or_elsereturns the result of evaluating the provided function
-
maptransformsOption[T]intoOption[U]by applying the provided function to the contained value ofSomeand leavingNoneunchanged -
and_thenreturns the result of applying the function (which itself returns anOption[U]) to the contained value ofSome, or returnsNoneif the original isNone -
or_elsereturns the originalOptionif it isSome, otherwise returns the result of the provided function (which returns anOption[T])
Creates an Option[T] with the Some and None variants and safely extracts the value:
from option import Option
some = Option.some("Hello World")
none = Option.none()
print(some.unwrap()) # Hello World
print(none.unwrap_or("Default value")) # Default value
# Using map to transform the value
result = some.map(lambda s: s.upper())
print(result.unwrap()) # HELLO WORLD
# Chaining with and_then
def safe_divide(x: int) -> Option[float]:
if x == 0:
return Option.none()
return Option.some(10 / x)
value = Option.some(2).and_then(safe_divide)
print(value.unwrap()) # 5.0
# Fallback with or_else
value = Option.none().or_else(lambda: Option.some(42))
print(value.unwrap()) # 42