Result
is obviously a result of some series of computations.
It might succeed with some resulting value.
Or it might return an error with some extra details.
Result
consist of two types: Success
and Failure
.
Success
represents successful operation result
and Failure
indicates that something has failed.
from returns.result import Result, Success, Failure
def find_user(user_id: int) -> Result['User', str]:
user = User.objects.filter(id=user_id)
if user.exists():
return Success(user[0])
return Failure('User was not found')
user_search_result = find_user(1)
# => Success(User{id: 1, ...})
user_search_result = find_user(0) # id 0 does not exist!
# => Failure('User was not found')
When is it useful?
When you do not want to use exceptions to break your execution scope.
Or when you do not want to use None
to represent empty values,
since it will raise TypeError
somewhere
and other None
exception-friends.
Result
(inner_value)[source]¶Bases: returns.primitives.container.GenericContainerTwoSlots
Base class for Failure and Success.
Failure
(inner_value)[source]¶Bases: returns.result.Result
Represents a calculation which has failed.
It should contain an error code or message. To help with readability you may alternatively use the alias ‘Failure’.
fix
(function)[source]¶Applies function to the inner value.
Applies ‘function’ to the contents of the ‘Success’ instance and returns a new ‘Success’ object containing the result. ‘function’ should accept a single “normal” (non-monad) argument and return a non-monad result.
Success
(inner_value)[source]¶Bases: returns.result.Result
Represents a calculation which has succeeded and contains the result.
To help with readability you may alternatively use the alias ‘Success’.
map
(function)[source]¶Applies function to the inner value.
Applies ‘function’ to the contents of the ‘Success’ instance and returns a new ‘Success’ object containing the result. ‘function’ should accept a single “normal” (non-monad) argument and return a non-monad result.