fptools.maybe

Pythonic FP - Maybe Monad

class pythonic_fp.fptools.maybe.MayBe
class pythonic_fp.fptools.maybe.MayBe(value: D)

Maybe monad, data structure wrapping a potentially missing value.

Immutable semantics

  • can store any item of any type, including None

  • can store any value of any type with one exception

  • immutable semantics, therefore made covariant

Warning

Hashability invalidated if contained value is not hashable.

bind(f: Callable[[D], MayBe]) MayBe

Flatmap MayBe with function f.

get() D | Never
get(alt: D) D

Return the contained value if it exists, otherwise an alternate value.

Warning

Unsafe method get. Will raise ValueError if MayBe empty and an alt return value not given. Best practice is to first check the MayBe in a boolean context.

Raises:

ValueError – when an alternate value is not provided but needed

map(f: Callable[[D], U]) MayBe

Map function f over contents.

static sequence(sequence_mb_u: Sequence[MayBe]) MayBe[Sequence]

Sequence a mutable indexable of type MayBe[~U]

If the iterated MayBe values are not all empty,

  • return a MayBe of the Sequence subtype of the contained values

  • otherwise return an empty MayBe