fptools.maybe

Pythonic FP - Maybe Monad

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

Maybe Monad

Data structure wrapping a potentially missing item.

Immutable semantics

  • can store any item of any type, including None

  • with one hidden implementation dependent exception

  • immutable semantics

Warning

Hashability invalidated if contained item is not hashable.

__init__() None
__init__(item: D) None
__hash__() int

Return hash(self).

__repr__() str

Return repr(self).

__eq__(other: object) bool

Return self==value.

get() D
get(alt: D) D

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

Warning

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

Parameters:

alt – an “optional” alternative item to return

Returns:

the contained item if it exists

Raises:

ValueError – when an alternate item is not provided but needed

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

Map function f over contents.

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

Flatmap MayBe with function f.

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

Sequence a subtype of Sequence[MayBe[U]].

Parameters:

sequence_mb_u – Sequence of type Maybe[U]

Returns:

MayBe of Sequence subtype if all items non-empty, otherwise an empty Maybe