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.
Get a value out
Section titled “Get a value out”Option.of(None).get_or_else(0) # 0Some(5).fold(0, lambda v: v * 2) # 10Nothing.fold(0, lambda v: v * 2) # 0Constructors
Section titled “Constructors”| Call | Result |
|---|---|
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 |
Crossing over
Section titled “Crossing over”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 equivalent
Section titled “Scala equivalent”Scala’s Option[A]: Some(value) and Nothing (Scala’s None). The same map,
filter, fold, get_or_else (getOrElse), and to_either (toRight).