Provides a Maybe class as a Python implementation of null-aware operators.
Likely abandoned. No release or commit for years (last release over 7 years ago).
pip install maybe-elseOverview
Provides a Maybe class which serves as a pseudo-implementation of null-aware operators in python:
- can be used to avoid common
var if var is not None else handle_none(var)structures - Null-aware item access
- Null-aware attribute access
- Null-aware chained method calls
- Can be combined with all arithmetic and bitwise operators
Installation
To install use pip:
$ pip install maybe-else
Or clone the repo:
$ git clone https://github.com/matthewgdv/maybe.git
$ python setup.py install
Usage
The simplest use-case is to wrap the value in the Maybe class and call Maybe.else_() with an alternative value. If the initial value was None,
the alternative value will be returned. Otherwise the original value will be returned.
Maybe(None).else_("other") # "other"
Maybe("hi").else_("other") # "hi"
More complex uses involve chaining item/attribute access and method calls off the initial value.
If at any point an IndexError or KeyError (item access), AttributeError (attribute access), or TypeError (method call) is raised, the alternative value will be returned
upon calling Maybe.else_(). Other exception classes are not caught by Maybe (intentionally) and will have be to handled normally.
Maybe("hi").monkeyweasel[3].else_("other") # "other"
Maybe({"one": "1"})["one"].isnumeric().else_("other") # True
Most operators can be used with Maybe. Actions involving operators will ignore TypeError, but other types of exceptions will have to be handled outside the Maybe construct.
(Maybe(8) / 2).else_("other") # 4.0
(Maybe("hi").upper() + "!").else_("other") # "HI!"
(Maybe(None) // 3).else_("other") # "other"
(Maybe(11) % 4).else_("other") # 3
If None would be returned as a result of operations performed on the Maybe object, then None will be returned from Maybe.else_(), rather than the alternative value.
This is because None is a legitimate output value, so long as it was not the original input value.
Maybe({1: "1"}).get(2).else_("other") # None