maybe monad¶
- final class pythonic_fp.fptools.maybe.MayBe¶
Bases:
GenericMaybe Monad
Data structure wrapping a potentially missing item.
immutable semantics
can store any item of any type, including
Nonehashable
- __init__() None¶
- __init__(item: D) None
init
Initialize MayBe with 1 or 0 items.
- param item:
Optional item for the MayBe instance.
Important
A
MayBeis immutable once initialized.MayBe()is not a singleton.
- __hash__() int¶
hash
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.
- returns:
True if not empty, False if empty.
- __len__() int¶
len
Zero or one items.
- __eq__(other: object) bool¶
equality comparison
Compare MayBe instance to another object. Compare first by identity, then value.
- returns:
True only if other object is a MayBe with a corresponding item, or both empty.
- __iter__() Iterator¶
iterate
- yields:
The contained item if non-empty.
- __repr__() str¶
repr string
Return the strings
‘MayBe()’ if empty
‘MayBe(repr_item)’ if not empty
Where
repr_item = repr(item).- returns:
A string to reproduce the MayBe.
- __str__() str¶
user string
Return the strings
‘MayBe(str_item)’ when not empty
‘MayBe()’ when empty
Where
str_item = str(item).- returns:
A string meaningful to an end user.
- 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 alternate 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 instance if not empty, otherwise itself.
- bind(f: Callable[[D], MayBe[U]]) MayBe[U]¶
Bind
Flatmap function f over the MayBe.
- param f:
Function to bind.
- returns:
A new MayBe instance if not empty, otherwise itself.
- static sequence(sequence_mb_u: Sequence[MayBe]) MayBe[Sequence]¶
Sequence
Sequence[MayBe[U]]->MayBe[Sequence[U]]- param sequence_mb_u:
A
SequenceofMayBeof the same type.- returns:
Empty
MayBeif one of theMayBeis 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``.