Skip to content
Pyrula

Option

Option is Some(value) or Nothing. It replaces None and the guard clauses that come with it. You chain operations and handle absence once, at the end.

from pyrula import Option, Some, Nothing
config = {"timeout": "30"}
timeout = (
Option.of(config.get("timeout")) # Some("30"), or Nothing if missing
.map(int) # Some(30)
.filter(lambda s: s > 0) # stays Some(30); Nothing if not positive
.get_or_else(10) # 30
)

map and filter are no-ops on Nothing, so the chain reads top to bottom without a single if x is not None.

Option.of(None).get_or_else(0) # 0
Some(5).fold(0, lambda v: v * 2) # 10
Nothing.fold(0, lambda v: v * 2) # 0
CallResult
Option.of(v)Nothing if v is None, else Some(v)
Option.when(test, v)Some(v) if test else Nothing
Option.from_callable(fn)Some(fn()), or Nothing if it raises
Option.sequence([...])Some of all values if none are Nothing

to_either(left) turns absence into an error. to_list() gives an empty or single-element IList.

Some(5).to_either("missing") # Ok(5)
Nothing.to_either("missing") # Err("missing")

Scala’s Option[A]: Some(value) and Nothing (Scala’s None). The same map, filter, fold, get_or_else (getOrElse), and to_either (toRight).