maybe monad

final class pythonic_fp.fptools.maybe.MayBe

Bases: Generic

Maybe Monad

Data structure wrapping a potentially missing item.

  • immutable semantics

  • can store any item of any type, including None

  • hashable

__init__() None
__init__(item: D) None

initialize

Initialize MayBe with 1 or 0 items.

param item:

Optional item for the MayBe.

Important

  • A MayBe is immutable once initialized.

  • MayBe() is not a singleton.

__hash__() int

hashability

If contained item hashable, use its hash value in the hash calculation, otherwise use item’s identity.

  • should be safe, the MayBe holds a reference to the item

  • lazily calculates hash value, then caches it

__bool__() bool

bool

Truthy when not empty.

__len__() int

len

Zero or one items.

__eq__(other: object) bool

equality comparison

Compare MayBe to another object. Compare first by identity, then value.

__iter__() Iterator

iterate

yields:

The contained item if non-empty.

__repr__() str

representation string

Return the strings

returns:

‘MayBe()’ if empty

returns:

‘MayBe(repr_item)’ if not empty where repr_item = repr(item).

__str__() str

user string

Return the strings

  • ‘MayBe(str_item)’ when not empty

  • ‘MayBe()’ when empty

Where str_item = str(item).

get() D
get(alt: D) D

get

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

param alt:

Optional alternative item to return if``MayBe`` empty.

returns:

The item if it exists.

raises ValueError:

When an alternate item is not provided but needed.

Warning

Unsafe method get will raise ValueError if the MayBe is empty and an alt return item not provided.

Tip

Best practice is to first check the MayBe in a boolean context.

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

Map

Map function f over the MayBe.

param f:

Function used for the map.

returns:

A new MayBe if not empty, otherwise self.

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

Bind

Flatmap function f over the contained item, if it exists.

param f:

Function to bind.

returns:

A new MayBe if not empty, otherwise self.

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

Sequence

Sequence[MayBe[U]] -> MayBe[Sequence[U]]

param sequence_mb_u:

A Sequence of MayBe of the same type.

returns:

Empty MayBe if one of the MayBe is empty.

,, note:

A sequenced empty ``Sequence[MayBe[U]]`` would produce
a ``MayBe`` of an empty ``Sequence``, not an empty
``MayBe``.

.. tip

    If above is confusing, replace the term "Sequence"
    above with a concrete example of a ``Sequence``
    like ``list`` or ``tuple``.