Container is a concept that allows you to write code around the existing wrapped values while maintaining the execution context.
List of supported containers:
We will show you container’s simple API of one attribute and several simple methods.
The main idea behind a container is that it wraps some internal state.
That’s what
._inner_value
is used for.
And we have several functions to create new containers based on the previous state. And we can see how this state is evolving during the execution.
We use two methods to create a new container from the previous one.
bind
and map
.
The difference is simple:
map
works with functions that return regular value
bind
works with functions that return new container of the same type
.bind
is used to literally bind two different containers together.
from returns.result import Result, Success
def may_fail(user_id: int) -> Result[int, str]:
...
# Can be assumed as either Success[int] or Failure[str]:
result: Result[int, str] = Success(1).bind(may_fail)
And we have .map
to use containers with regular functions.
from typing import Any
from returns.result import Success, Result
def double(state: int) -> int:
return state * 2
result: Result[int, Any] = Success(1).map(double)
# => Success(2)
result: Result[int, Any] = result.map(lambda state: state + 1)
# => Success(3)
The same work with built-in functions as well:
from returns.io import IO
IO('bytes').map(list)
# => <IO: ['b', 'y', 't', 'e', 's']>
Note:
All containers support these methods.
When talking about error handling we use a concept of Railway oriented programming. It mean that our code can go on two tracks:
Successful one: where everything goes perfectly: HTTP requests work, database is always serving us data, parsing values does not failed
Failed one: where something went wrong
We can switch from track to track: we can fail something or we can rescue the situation.
We also support two special methods to work with “failed”
types like Failure
:
.fix
is the opposite of map
method
that works only when container is in failed state
.rescue
is the opposite of bind
method
that works only when container is in failed state
fix
can be used to fix some fixable errors
during the pipeline execution:
from returns.result import Failure, Result
def double(state: int) -> float:
return state * 2.0
result: Result[float, int] = Failure(1).fix(double)
# => Success(2.0)
rescue
should return one of Success
or Failure
types.
It can also rescue your flow and get on the successful track again:
from returns.result import Result, Failure, Success
def tolerate_exception(state: Exception) -> Result[int, Exception]:
if isinstance(state, ZeroDivisionError):
return Success(0)
return Failure(state)
result: Result[int, Exception] = Failure(
ZeroDivisionError(),
).rescue(tolerate_exception)
# => Success(0)
result2: Result[int, Exception] = Failure(
ValueError(),
).rescue(tolerate_exception)
# => Failure(ValueError())
Note:
Not all containers support these methods.
IO cannot be fixed or rescued.
And we have two more functions to unwrap inner state of containers into a regular types:
.value_or
returns a value if it is possible, returns default_value
otherwise
.unwrap
returns a value if it is possible, raises UnwrapFailedError
otherwise
from returns.result import Failure, Success
Success(1).value_or(None)
# => 1
Success(0).unwrap()
# => 0
Failure(1).value_or(default_value=100)
# => 100
Failure(1).unwrap()
# => Traceback (most recent call last): UnwrapFailedError
The most user-friendly way to use unwrap
method is with pipeline.
We even discourage using .unwrap()
without a @pipeline
.
For failing containers you can
use .failure
to unwrap the failed state:
Failure(1).failure()
# => 1
Success(1).failure()
# => Traceback (most recent call last): UnwrapFailedError
Be careful, since this method will raise an exception
when you try to failure
a successful container.
Note:
Not all containers support these methods.
IO cannot be unwrapped.
We like to think of returns
as immutable structures.
You cannot mutate the inner state of the created container,
because we redefine __setattr__
and __delattr__
magic methods.
You cannot also set new attributes to container instances,
since we are using __slots__
for better performance and strictness.
Well, nothing is really immutable in python, but you were warned.
We try to make our containers optionally type safe.
What does it mean?
It is still good old python
, do whatever you want without mypy
If you are using mypy
you will be notified about type violations
We also ship PEP561
compatible .pyi
files together with the source code.
In this case these types will be available to users
when they install our application.
We also ship custom mypy
plugins to overcome some existing problems,
please make sure to use them,
since they increase your developer experience and type-safety:
decorator_plugin
to solve untyped decorator issue
[mypy]
plugins =
returns.contrib.mypy.decorator_plugin
You can have a look at the suggested mypy
configuration
in our own repository.
You can and should compose different containers together. Here’s the full table of compositions that make sense:
IO[Result[A, B]]
✅
Result[IO[A], B]
✅
IO[Maybe[A]]
✅
Maybe[IO[A]]
✅
IO[IO[A]]
🚫
Result[A, IO[A]]
🚫
Result[Maybe[A], B]
🚫
Result[A, Maybe[B]]
🚫
Result[Result[A, B], C]
🚫
Result[A, Result[B, C]]
🚫
Maybe[Result[A, B]]
🚫
You can use converters to convert Maybe
and Result
containers.
So, you don’t have to compose them.
We have several helper functions
to convert containers from Maybe
to Result
and back again:
maybe_to_result
that converts Maybe
to Result
result_to_maybe
that converts Result
to Maybe
That’s how they work:
from returns.converters import maybe_to_result, result_to_maybe
from returns.maybe import Maybe
from returns.result import Result
result: Result[int, Exception]
maybe: Maybe[int] = result_to_maybe(result)
new_result: Result[int, None] = maybe_to_result(maybe)
Take a note, that type changes.
Also, take a note that Success(None)
will be converted to Nothing
.
Container
(inner_value)[source]¶Bases: returns.primitives.container._BaseContainer
Represents a “context” in which calculations can be executed.
You won’t create ‘Container’ instances directly. Instead, sub-classes implement specific contexts. containers allow you to bind together a series of calculations while maintaining the context of that specific container.
This is an abstract class with the API declaration.
_inner_value
¶Wrapped internal immutable state.
FixableContainer
[source]¶Bases: object
Represents containers that can be fixed and rescued.
fix
(function)[source]¶Applies ‘function’ to the contents of the functor.
And returns a new functor value.
Works for containers that represent failure.
Is the opposite of map()
.
ValueUnwrapContainer
[source]¶Bases: object
Represents containers that can unwrap and return its wrapped value.
GenericContainerOneSlot
(inner_value)[source]¶Bases: typing.Generic
, returns.primitives.container.Container
Base class for containers with one typed slot.
Use this type for generic inheritance only.
Use Container
as a general type for polymorphism.
GenericContainerTwoSlots
(inner_value)[source]¶Bases: typing.Generic
, returns.primitives.container.Container
Base class for containers with two typed slot.
Use this type for generic inheritance only.
Use Container
as a general type for polymorphism.