Skip to content
maslina524 edited this page Apr 20, 2026 · 1 revision

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.

Classmethods

  • some returns an Option containing the given value (Some variant)
  • none returns an Option representing no value (None variant)

Querying the variant

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:

  • expect panics with a provided custom message
  • unwrap panics with a generic message
  • unwrap_or returns the provided default value
  • unwrap_or_else returns the result of evaluating the provided function

Transforming contained values

  • map transforms Option[T] into Option[U] by applying the provided function to the contained value of Some and leaving None unchanged
  • and_then returns the result of applying the function (which itself returns an Option[U]) to the contained value of Some, or returns None if the original is None
  • or_else returns the original Option if it is Some, otherwise returns the result of the provided function (which returns an Option[T])

Examples

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

Clone this wiki locally