maybetype module¶
- class maybetype.Err(val: E)¶
Indicates a failed result of type
E.
- class maybetype.Maybe(val: T | None)¶
Wraps a value that may be
TorNone, providing methods for conditionally using that value or short-circuiting toNonewithout longer checks.- and_then(func: Callable[[T], Maybe[U]]) Maybe[U]¶
Returns the result of
func(which must return aMaybe) called with the wrapped value ifSome, otherwise returnsNothing.
- attr(name: str, default: U | None = None, typ: type[U] | None = None) Maybe¶
Attempts to access an attribute
nameon the wrapped object, returning aSomeinstance wrapping the the 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.
- bind(func: Callable[[T], Maybe[U]]) Maybe[U]¶
Returns the result of
funccalled with the wrapped value as its argument ifSome, otherwise returnsNothing.
- cast(typ: type[U]) Maybe¶
Returns a reference to this instance after casting its type as
Maybe[typ].
- static cat(vals: Iterable[Maybe[T]]) list[T]¶
Takes an iterable of
Maybeand returns a list of the unwrapped values of allSomeobjects.>>> 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
selfifSomeandpredicatecalled with this instance’s wrapped value returnsTrue, 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 aTypeErrorif 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: Any, typ: type[U] | None = None, *, err: bool = False, default: U | None = None) 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 – By default,
IndexErrorandKeyErrorare not raised when__getitem__is called on the wrapped value, andNothingis returned instead. SettingerrtoTrueallows these errors to be raised as they normally would. Note that if__getitem__did not exist on the wrapped value in the first placed (such as withNothing), no error is raised, andNothingis returned regardless.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.
- map(func: Callable[[T], U]) Maybe[U]¶
Returns a new
Maybewith the result of callingfuncwith the wrapped value of this instance ifSome, otherwise returnsNothing.
- ok_or(err: E) Result[T, E]¶
Converts this
Maybe[T]to aResult[T, E].Some(v)becomesOk(v)wherevis the wrapped value, andNothingbecomesErr(err).
- ok_or_else(err: Callable[[], E]) Result[T, E]¶
Converts this
Maybe[T]to aResult[T, E].Some(v)becomesOk(v)wherevis the wrapped value, andNothingbecomesErr(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, otherwise returnsNothing.
- static sequence(vals: Iterable[Maybe[T]]) Maybe[list[T]]¶
Returns
Nothingif any ofvalsisNothing, otherwise returns aSomeof 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 this instance’s 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], Any]¶
Transposes a
MaybeofResultto aResultofMaybe.Some(Ok(x))becomesOk(Some(x)),Some(Err(x))becomesErr(x),NothingbecomesOk(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.
- static try_int(val: Any) Maybe[int]¶
Attempts to convert
valto anint, returning aSome-wrappedintif successful, orNothingon failure.
- unwrap(exc: str | Exception | Callable[[], Never] = 'unwrapped Nothing') T¶
Returns the wrapped value if
Some, otherwise raisesValueErroror fails according toexc.- Parameters:
exc – The exception to raise when unwrapping
Nothing. If a string is given,ValueErroris raised asValueError(exc). If anExceptionobject 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. IfNothing,(Nothing, Nothing)is returned. Otherwise,TypeErroris raised.- Raises:
TypeError – The wrapped value is not a 2-tuple.
- class maybetype.NothingType(_: None = None)¶
- 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. TheResultclass itself should only be using for type annotations and not instancing; use theOkandErrconstructors otherwise.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: type[U], e_type: 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 aTypeErrorif 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
funcmapped onto the wrapped value ifOk, otherwise applyingdefaultto theErrvalue and returning that.
- 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 toexcwith the wrapped value as the passed argument ifexcis callable.- Parameters:
exc – If
None, aResultUnwrapErroris raised with the wrapped value as the exception message. 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 toexcwith the wrapped value as the passed argument ifexcis callable.- Parameters:
exc – If
None, aResultUnwrapErroris raised with the wrapped value as the exception message. 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 callsfuncwith the wrappedErrvalue and returns its result.
- class maybetype.Some(val: T)¶
- maybetype.maybe(val: T | None, predicate: ~collections.abc.Callable[[T], bool] = <function <lambda>>) Maybe¶
Returns a
Someinstance wrappingvalif eithervalis notNoneorpredicate(val)isTrue, otherwise returns theNothingsingleton.- 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).