maybetype module¶
A basic implementation of a maybe/option type in Python, as well as a Result type.
- class maybetype.Err(val: E)¶
Indicates a failed result of type
E.
- class maybetype.Maybe(_val: T)¶
Wraps a possible value of type
T.This is a base class that is subclassed by
SomeandNothingType, and will raiseerrors.MaybeInstanceErrorif instanced directly- and_then(func: Callable[[T], Maybe[U]]) Maybe[U]¶
Returns
func(val)ifSome, otherwise returnsNothing.
- as_list() list[T]¶
Returns a list containing the wrapped value if
Some, otherwise returns an empty list.
- as_tuple() tuple[T] | tuple[()]¶
Returns a tuple containing the wrapped value if
Some, otherwise returns an empty tuple.
- attr(name: str, default: U | None = None, _typ: type[U] | None = None) Maybe¶
Attempts to access an attribute
namein the wrapped value, returningSomewrapping the the attribute’s value if it exists, orNothingotherwise.- Parameters:
name – The name of the attribute to access.
default – An optional default value to use if the attribute does not exist, returning
Some(default)in that case.typ – Specifies the generic type of the resulting
Maybe. This does not affect the value’s real type at runtime; it is only used for type checkers. This is generally unnecessary if thedefaultparameter is given, as the type will be inferred from its value.
- static cat(vals: Iterable[Maybe[T]]) list[T]¶
Takes an iterable of
Maybeobjects and returns a list of the unwrapped values of theSomeobjects.>>> vals = [maybe(5), maybe(None), maybe(10), maybe(None)] >>> assert vals == [Some(5), Nothing, Some(10), Nothing] >>> assert Maybe.cat(vals) == [5, 10]
- filter(predicate: Callable[[T], bool]) Maybe[T]¶
Returns
selfif it isSomeandpredicate(val)isTrue, otherwise returnsNothing.>>> assert Some(1).filter(lambda n: n > 0).unwrap() == 1 >>> assert Some(1).filter(lambda n: n > 1) is Nothing >>> assert Nothing.filter(lambda n: n > 1) is Nothing
- flatten() Maybe[T]¶
Returns a new
Maybe[T]from aMaybe[Maybe[T]].Only flattens one level at a time, and will raise a
TypeErrorif called when the wrapped value is notMaybe.Note
It’s expected that the resulting type of this method may not be correctly inferred and will return returning
Maybe[Unknown]. For now,cast()can be used to specify a type for type checkers.- Raises:
TypeError – The wrapped value is not
Maybe.
- get(accessor: object, _typ: type[U] | None = None, *, err: bool = False, default: U | EllipsisType = Ellipsis) Maybe¶
Attempts to access an item by
accessoron the wrapped object if it supports__getitem__.If it does not, or if the value does not exist (list index out of range, key does not exist on a dictionary, etc.),
Nothingis returned.- Parameters:
typ – Specifies the generic type of the resulting
Maybe. No conversion is performed; this argument is only for typing purposes.err – Whether to allow
IndexErrorandKeyErrorto propagate from the__getitem__call. WhenFalse(default), these errors are ignored andNothingis returned.default – Specifies an alternate value to return a
Someof instead of returningNothing.
- inspect(func: Callable[[T], Any]) Self¶
Calls a function with the wrapped value if
Some, otherwise does nothing. Returns this instance.
- ok_or(err: E) Result[T, E]¶
Converts this
Maybe[T]to aResult[T, E].Some(val)becomesOk(val),NothingbecomesErr(err).
- ok_or_else(err: Callable[[], E]) Result[T, E]¶
Converts this
Maybe[T]to aResult[T, E].Some(val)becomesOk(val),NothingbecomesErr(err()).
- reduce(other: Maybe[U], func: Callable[[T, U], R], *, strict: bool = False) Maybe[T] | Maybe[U] | Maybe[R]¶
Reduces the values of two
Maybeinstances to one value returned in a newMaybeusingfunc.If only one of
selfandotherisSome, that instance is returned. If neither are,Nothingis returned.>>> assert Some(1).reduce(Some(2), lambda a, b: a + b) == Some(3) >>> assert Some(1).reduce(Nothing, lambda a, b: a + b) == Some(1) >>> assert Nothing.reduce(Some(2), lambda a, b: a + b) == Some(2) >>> assert Nothing.reduce(Nothing, lambda a, b: a + b) is Nothing
- Parameters:
strict – If
True, returnsNothingifselfandotherare not bothSome.
- replace(new_val: T) Maybe[T]¶
Replaces the wrapped value with
new_valand returns a reference to this same instance ifSome.
- static sequence(vals: Iterable[Maybe[T]]) Maybe[list[T]]¶
Returns
Nothingif any ofvalsisNothing, otherwise returnsSomeof a list of unwrapped items ofvals.>>> assert Maybe.sequence([Some(1), Some(2), Some(3)]) == Some([1, 2, 3]) >>> assert Maybe.sequence([Some(1), Nothing, Some(3)]) is Nothing
- then(func: Callable[[T], U]) U | None¶
Returns
funccalled with the wrapped value ifSome, otherwise returnsNone.- Parameters:
func – A
Callablewhich takes a type of the possible wrapped value (T) and can return any type (U).
- transpose() Result[Maybe[Any], E]¶
Transposes a
MaybeofResultto aResultofMaybe.Some(Ok(x))becomesOk(Some(x)),Some(Err(x))becomesErr(x),NothingbecomesOk(Nothing).>>> assert Some(Ok(1)).transpose() == Ok(Some(1)) >>> assert Some(Err(0)).transpose() == Err(0) >>> assert Nothing.transpose() == Ok(Nothing)
Note
Currently the type information of the wrapped
Resultcan’t be known and used for the return type of this method, so it will returnResult[Maybe[Any], Any]. You can use thecast()method to work around this for now.- Raises:
TypeError – The wrapped value is not
Result.
- unwrap(exc: str | Exception | Callable[[], Never] = 'unwrapped Nothing') T¶
Returns the wrapped value if
Some, otherwise raisesValueErroror fails according toexc.- Parameters:
exc – If a string is given,
ValueErroris raised with the string as its argument. If anExceptioninstance is given, it is raised. If aCallableis given, it is called with no arguments.
- unwrap_or(other: T) T¶
Returns the wrapped value if
Some, otherwise returnsother.
- unwrap_or_else(func: Callable[[], T]) T¶
Returns the wrapped value if
Some, otherwise returns the result of callingfunc.
- unzip() tuple[Maybe[T], Maybe[U]]¶
Returns
(Some(a), Some(b))if the wrapped value is a tuple of two items.If
Nothing,(Nothing, Nothing)is returned.- Raises:
TypeError – The wrapped value is not a 2-tuple.
- class maybetype.NothingType(_: None = None)¶
Subclass of
Mayberepresenting no value.
- class maybetype.Ok(val: T)¶
Indicates a successful result of type
T.
- class maybetype.Result(_val: T | E)¶
A class which wraps a value of
Tif the instance is of the subclassOk, or wrapsEifErr.The
Resultclass itself should only be using for type annotations and not instancing; use theOkandErrconstructors otherwise.ResultInitErroris raised ifResult()is called directly.Okinstances are always truthy, whileErrinstances are always falsy.- and_then(func: Callable[[T], Result[U, E]]) Result[U, E]¶
Returns
funccalled with the wrapped value ifOk, otherwise returns this instance.
- cast(_t: type[U], _e: type[F]) Result¶
Returns a reference to this instance after casting its type as
Result[t_type, e_type].
- flatten() Result[T, E]¶
Returns a new
Result[T, E]from a``Result[Result[T, E], E]``.Only flattens one level at a time, and will raise a
TypeErrorif called when the wrapped value is notResult.Note
It’s expected that the resulting type of this method may not be correctly inferred and will return returning
Result[Unknown, Unknown]. For now,cast()can be used to specify a type for type checkers.- Raises:
TypeError – The wrapped value is not
Result.
- inspect(func: Callable[[T], Any]) Self¶
Calls a function with the wrapped value if
Ok, otherwise does nothing. Returns this instance.
- inspect_err(func: Callable[[E], Any]) Self¶
Calls a function with the wrapped value if
Err, otherwise does nothing. Returns this instance.
- map(func: Callable[[T], U]) Result[U, E]¶
Returns a new
Resultwithfuncmapped onto anOkvalue, leaving anErrunmodified.
- map_err(func: Callable[[E], F]) Result[T, F]¶
Returns a new
Resultwithfuncmapped onto anErrvalue, leaving anOkunmodified.
- map_or(default: U, func: Callable[[T], U]) U¶
Returns
funcmapped onto the wrapped value ifOk, otherwise returnsdefault.
- map_or_else(default: Callable[[E], U], func: Callable[[T], U]) U¶
Returns the result of calling
funcwith the wrapped value ifOk, otherwise callsdefault.
- transpose() Maybe[Result[T, E]]¶
Transposes a
ResultofMaybeto aMaybeofResult.Ok(Nothing)becomesNothing,Ok(Some(x))becomesSome(Ok(x)), andErr(x)becomesSome(Err(x)).- Raises:
TypeError – This is an
Okinstance and the wrapped value is notMaybe.
- unwrap(exc: str | type[Exception] | Callable[[E], Never] = <class 'maybetype.errors.ResultUnwrapError'>) T¶
Returns the wrapped value if
Ok, otherwise raises an error according toexc.- Parameters:
exc – By default,
ResultUnwrapErroris raised with the wrapped value as the exception argument. If given a string,ResultUnwrapErroris raised with the message format{msg}: {repr(val)}, wherevalis the wrappedErrvalue. If given anExceptiontype, that type of exception is raised with the wrapped value as the exception argument. If given aCallable,excis called with the wrapped value as the passed argument.
- unwrap_err(exc: str | type[Exception] | Callable[[E], Never] = <class 'maybetype.errors.ResultUnwrapError'>) E¶
Returns the wrapped value if
Err, otherwise raises an error according toexc.- Parameters:
exc – By default,
ResultUnwrapErroris raised with the wrapped value as the exception argument. If given a string,ResultUnwrapErroris raised with the message format{msg}: {repr(val)}, wherevalis the wrappedOkvalue. If given anExceptiontype, that type of exception is raised with the wrapped value as the exception argument. If given aCallable,excis called with the wrapped value as the passed argument.
- unwrap_or(default: T) T¶
Returns the wrapped value if
Ok, otherwise returnsdefault.
- unwrap_or_else(func: Callable[[E], T]) T¶
Returns the wrapped value if
Ok, otherwise returnsfunccalled with the wrapped value.
- class maybetype.Some(val: T)¶
Subclass of
Mayberepresenting a present value of typeT.
- maybetype.maybe(val: None, predicate: Callable[[T], bool] = lambda v: ...) NothingType¶
- maybetype.maybe(val: T | None, predicate: Callable[[T], bool] = lambda v: ...) Maybe[T]
Returns
NothingifvalisNoneornot predicate(val), otherwise returnsSome(val).- Parameters:
val – A value to wrap.
predicate – A function that must return
Trueforpredicate(val)in addition tovalnot beingNonein order for aSometo be returned;maybe(val, predicate)is then effectively shorthand formaybe(val).filter(predicate).
- maybetype.maybe_exc(fn: Callable[[], T], *exc: type[Exception] | tuple[type[Exception], str | Pattern]) Maybe¶
Returns
Nothingiffn()raises the specified error(s), otherwise returnsSomewith its result.>>> assert maybe_exc(lambda: int('1'), ValueError) == Some(1) >>> assert maybe_exc(lambda: int('one'), ValueError) == Nothing >>> assert maybe_exc(lambda: int('one'), (ValueError, r'invalid literal for int\(\).*')) == Nothing
- Parameters:
fn – A function to call which takes no arguments.
exc – One or more either exception types or a tuple of an exception type and regex pattern to match the raised exception’s message against, where if any of the given exceptions are raised (and if a pattern is given,
str(e)whereeis the raised exception must match it),Nothingis returned instead of propagating the exception. If any exceptions not listed are raised or a pattern is given for an exception and it does not match, the exception is raised normally.