Skip to content

Option API Reference

API documentation for the Option type and related classes.

Type Alias

Option[T] = Some[T] | Nothing

A type representing an optional value: either Some[T] (present) or Nothing (absent).


Some

Some

Some(value: T)

Bases: Generic[T]

Some variant of Option containing a value.

PARAMETER DESCRIPTION
value

The value to wrap.

TYPE: T

Example
option = Some(42)
option.unwrap()  # 42
option.is_some()  # True

inspect class-attribute instance-attribute

inspect = tee

is_some

is_some() -> Literal[True]

Return True (this is Some).

is_nothing

is_nothing() -> Literal[False]

Return False (this is not Nothing).

map

map(fn: Callable[[T], U]) -> Some[U]

Transform the Some value.

map_async async

map_async(
    fn: Callable[[T], Coroutine[Any, Any, U]],
) -> Some[U]

Transform Some value with async function.

map_or

map_or(default: U, fn: Callable[[T], U]) -> U

Apply fn to the Some value.

map_or_else

map_or_else(
    default_fn: Callable[[], U], fn: Callable[[T], U]
) -> U

Apply fn to the Some value.

and_then

and_then(
    fn: Callable[[T], Some[U] | _NothingType],
) -> Some[U] | _NothingType

Chain Option-returning operation.

and_then_async async

and_then_async(
    fn: Callable[
        [T], Coroutine[Any, Any, Some[U] | _NothingType]
    ],
) -> Some[U] | _NothingType

Chain async Option-returning operation.

or_else

or_else(
    fn: Callable[[], Some[U] | _NothingType],
) -> Some[T]

Return self (has value, no need to recover).

or_else_async async

or_else_async(
    fn: Callable[
        [], Coroutine[Any, Any, Some[U] | _NothingType]
    ],
) -> Some[T]

Return self (has value, no need to recover).

filter

filter(
    predicate: Callable[[T], bool],
) -> Some[T] | _NothingType

Return Some if predicate passes, else Nothing.

unwrap

unwrap() -> T

Return the Some value.

unwrap_or

unwrap_or(default: object) -> T

Return the Some value, ignoring the default.

unwrap_or_else

unwrap_or_else(fn: Callable[[], U]) -> T

Return the Some value, ignoring the function.

unwrap_or_raise

unwrap_or_raise(exc: BaseException) -> T

Return the Some value, ignoring the exception.

expect

expect(msg: str) -> T

Return the Some value.

tee

tee(fn: Callable[[T], Any]) -> Some[T]

Execute fn for side effects, return self.

inspect_nothing

inspect_nothing(fn: Callable[[], Any]) -> Some[T]

Return self (not Nothing, skip fn).

ok_or

ok_or(err: E) -> Ok[T] | Err[E]

Convert to Ok with the Some value.

ok_or_else

ok_or_else(fn: Callable[[], E]) -> Ok[T] | Err[E]

Convert to Ok with the Some value.

flatten

flatten() -> Some[U] | _NothingType

Flatten nested Option.

zip

zip(
    other: Some[U] | _NothingType,
) -> Some[tuple[T, U]] | _NothingType

Zip with another Option.

zip_with

zip_with(
    other: Some[U] | _NothingType,
    fn: Callable[[T, U], Any],
) -> Some[Any] | _NothingType

Zip with another Option using a combining function.

xor

xor(
    other: Some[U] | _NothingType,
) -> Some[T] | Some[U] | _NothingType

Return Some if exactly one is Some, else Nothing.

to_tuple

to_tuple() -> tuple[T]

Convert to single-element tuple.


Nothing (NOTHING)

The Nothing type represents the absence of a value. NOTHING is the singleton instance.

from unwrappy import NOTHING, Option

absent: Option[int] = NOTHING

Methods

All methods on Nothing return appropriate "empty" values:

Method Return Value
is_some() False
is_nothing() True
map(fn) NOTHING
and_then(fn) NOTHING
or_else(fn) Result of fn()
filter(pred) NOTHING
unwrap() Raises UnwrapError
unwrap_or(default) default
unwrap_or_else(fn) Result of fn()
ok_or(err) Err(err)
flatten() NOTHING
zip(other) NOTHING
xor(other) other if other is Some, else NOTHING
to_tuple() ()

LazyOption

LazyOption

LazyOption(
    source: Awaitable[Some[T] | _NothingType]
    | Some[T]
    | _NothingType,
    operations: tuple[OptionOperation, ...] = (),
)

Bases: Generic[T]

Lazy Option with deferred execution for clean async chaining.

LazyOption builds a pipeline of operations that execute only when .collect() is called. All methods accept both sync and async functions transparently.

Example
async def fetch_config(key: str) -> Option[str]: ...

result = await (
    LazyOption.from_awaitable(fetch_config("api_key"))
    .map(str.upper)
    .filter(lambda s: len(s) > 0)
    .collect()
)
From an existing Option
result = await Some(5).lazy().map(lambda x: x * 2).collect()
result  # Some(10)

inspect class-attribute instance-attribute

inspect = tee

from_option classmethod

from_option(
    option: Some[T] | _NothingType,
) -> LazyOption[T]

Create LazyOption from an existing Option.

from_awaitable classmethod

from_awaitable(
    awaitable: Awaitable[Some[T] | _NothingType],
) -> LazyOption[T]

Create LazyOption from a coroutine/awaitable that returns Option.

some classmethod

some(value: U) -> LazyOption[U]

Create LazyOption from a value.

nothing classmethod

nothing() -> LazyOption[Any]

Create LazyOption from Nothing.

map

map(
    fn: Callable[[T], U | Awaitable[U]],
) -> LazyOption[U]

Transform Some value. fn can be sync or async.

and_then

and_then(
    fn: Callable[
        [T],
        Some[U]
        | _NothingType
        | Awaitable[Some[U] | _NothingType],
    ],
) -> LazyOption[U]

Chain Option-returning function. fn can be sync or async.

or_else

or_else(
    fn: Callable[
        [],
        Some[T]
        | _NothingType
        | Awaitable[Some[T] | _NothingType],
    ],
) -> LazyOption[T]

Recover from Nothing. fn can be sync or async.

filter

filter(
    predicate: Callable[[T], bool | Awaitable[bool]],
) -> LazyOption[T]

Filter based on predicate. predicate can be sync or async.

tee

tee(fn: Callable[[T], Any]) -> LazyOption[T]

Side effect on Some value. fn can be sync or async.

inspect_nothing

inspect_nothing(fn: Callable[[], Any]) -> LazyOption[T]

Side effect on Nothing. fn can be sync or async.

flatten

flatten() -> LazyOption[U]

Flatten nested LazyOption[Option[U]] to LazyOption[U].

collect async

collect() -> Some[T] | _NothingType

Execute the lazy chain and return the final Option.


Type Guards

is_some

is_some

is_some(
    option: Some[T] | _NothingType,
) -> TypeIs[Some[T]]

Type guard to check if an option is Some.

Unlike the .is_some() method, this standalone function enables proper type narrowing in conditional branches. This is necessary because Python's type system doesn't support narrowing based on method return types.

PARAMETER DESCRIPTION
option

The Option to check.

TYPE: Some[T] | _NothingType

RETURNS DESCRIPTION
TypeIs[Some[T]]

True if option is Some, with the type narrowed to Some[T].

Example
from unwrappy import Option, Some, Nothing, is_some

def get_value(opt: Option[int]) -> int:
    if is_some(opt):
        return opt.unwrap()  # Type checker knows opt is Some[int]
    return 0

is_nothing

is_nothing

is_nothing(
    option: Some[T] | _NothingType,
) -> TypeIs[_NothingType]

Type guard to check if an option is Nothing.

Unlike the .is_nothing() method, this standalone function enables proper type narrowing in conditional branches. This is necessary because Python's type system doesn't support narrowing based on method return types.

PARAMETER DESCRIPTION
option

The Option to check.

TYPE: Some[T] | _NothingType

RETURNS DESCRIPTION
TypeIs[_NothingType]

True if option is Nothing, with the type narrowed to _NothingType.

Example
from unwrappy import Option, Some, Nothing, is_nothing

def describe(opt: Option[int]) -> str:
    if is_nothing(opt):
        return "empty"  # Type checker knows opt is Nothing
    return "has value"

Utility Functions

from_nullable

from_nullable

from_nullable(value: T | None) -> Some[T] | _NothingType

Convert a nullable value to Option.

PARAMETER DESCRIPTION
value

A value that may be None.

TYPE: T | None

RETURNS DESCRIPTION
Some[T] | _NothingType

Some(value) if value is not None, otherwise Nothing.

Example
from_nullable(42)    # Some(42)
from_nullable(None)  # Nothing

sequence_options

sequence_options

sequence_options(
    options: Iterable[Some[T] | _NothingType],
) -> Some[list[T]] | _NothingType

Collect an iterable of Options into an Option of list.

Fails fast on the first Nothing encountered. If all Options are Some, returns Some containing a list of all values.

PARAMETER DESCRIPTION
options

Iterable of Option values to collect.

TYPE: Iterable[Some[T] | _NothingType]

RETURNS DESCRIPTION
Some[list[T]] | _NothingType

Some(list) if all are Some, otherwise Nothing.

Example
sequence_options([Some(1), Some(2), Some(3)])  # Some([1, 2, 3])
sequence_options([Some(1), NOTHING, Some(3)])  # Nothing
sequence_options([])  # Some([])

traverse_options

traverse_options

traverse_options(
    items: Iterable[U],
    fn: Callable[[U], Some[T] | _NothingType],
) -> Some[list[T]] | _NothingType

Map a function over items and collect Options.

Equivalent to sequence_options(map(fn, items)) but more efficient. Fails fast on the first Nothing encountered.

PARAMETER DESCRIPTION
items

Iterable of items to process.

TYPE: Iterable[U]

fn

Function returning Option for each item.

TYPE: Callable[[U], Some[T] | _NothingType]

RETURNS DESCRIPTION
Some[list[T]] | _NothingType

Some(list) if all succeed, otherwise Nothing.

Example
def safe_sqrt(x: float) -> Option[float]:
    return Some(x ** 0.5) if x >= 0 else NOTHING

traverse_options([4, 9, 16], safe_sqrt)  # Some([2.0, 3.0, 4.0])
traverse_options([4, -1, 16], safe_sqrt)  # Nothing