Optionals¶
Satella provides a set of routines to use with optionals:
-
satella.coding.optionals.
call_if_nnone
(clbl: Optional[Callable[[...], V]], *args, **kwargs) → Optional[V]¶ Call clbl with provided arguments, but only if clbl is not None.
If it’s None, then None will be returned. Else, the result of this callable will be returned.
Parameters: - clbl – callable to call, or a None
- args – positional arguments to provide to clbl
- kwargs – keyword arguments to provide to clbl
Returns: return value or None
-
satella.coding.optionals.
iterate_if_nnone
(iterable: Optional[Iterable[T_co]]) → Iterable[T_co]¶ Return a generator iterating over every element of iterable if it’s not None.
If it’s None, return an empty generator
Parameters: iterable – iterable to iterate over Returns: an empty generator if iterable is none, else an iterator over iterable
-
class
satella.coding.optionals.
Optional
(obj)¶ A wrapper for your classes, that does nothing if the object passed in is None. It will return an empty Optional in that case.
Usage example:
>>> may_be_none = None >>> Optional(may_be_none).cancel().result()
So far operations supported:
- calling
- getattr
- getitem/setitem/delitem
- testing for truth
- comparison (with nonexistent elements always comparing false)
- membership test (with nonexistent elements always returning false)
Warning
Returned objects via getattr and getitem are NOT wrapped in an Optional. You need to do it by hand or just file an issue. I’ll add that when I need it.
Parameters: obj – object to wrap
To extract the value from an Optional
you may use:
-
satella.coding.optionals.
extract_optional
(v: Union[T, satella.coding.optionals.Optional[~T][T]]) → T¶ If v is an optional, extract the value that it wraps. If it is not, return v
Parameters: v – value to extract the value from Returns: resulting value