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
initialize
Initialize
MayBewith 1 or 0 items.- param item:
Optional item for the
MayBe.
Important
A
MayBeis 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
MayBeholds a reference to the itemlazily 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
MayBeto another object. Compare first by identity, then value.
- __iter__() Iterator¶
iterate
- yields:
The contained
itemif 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
getwill raiseValueErrorif theMayBeis empty and analtreturn item not provided.Tip
Best practice is to first check the
MayBein a boolean context.
- map(f: Callable[[D], U]) MayBe¶
Map
Map function
fover theMayBe.- param f:
Function used for the map.
- returns:
A new
MayBeif not empty, otherwiseself.
- bind(f: Callable[[D], MayBe[U]]) MayBe[U]¶
Bind
Flatmap function
fover the contained item, if it exists.- param f:
Function to bind.
- returns:
A new
MayBeif not empty, otherwiseself.
- 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``.