Make your functions return something meaningful, typed, and safe!
Provides a bunch of primitives to write declarative business logic
Enforces better architecture
Fully typed with annotations and checked with mypy
, PEP561 compatible
Pythonic and pleasant to write and to read (!)
Support functions and coroutines, framework agnostic
Result container that let’s you to get rid of exceptions
IO marker that marks all impure operations and structures them
Please, make sure that you are also aware of Railway Oriented Programming.
Consider this code that you can find in any python
project.
import requests
def fetch_user_profile(user_id: int) -> 'UserProfile':
"""Fetches UserProfile dict from foreign API."""
response = requests.get('/api/users/{0}'.format(user_id))
response.raise_for_status()
return response.json()
Seems legit, does not it?
It also seems like a pretty straight forward code to test.
All you need is to mock requests.get
to return the structure you need.
But, there are hidden problems in this tiny code sample that are almost impossible to spot at the first glance.
import requests
from returns.result import Result, pipeline, safe
class FetchUserProfile(object):
"""Single responsibility callable object that fetches user profile."""
@pipeline
def __call__(self, user_id: int) -> Result['UserProfile', Exception]:
"""Fetches UserProfile dict from foreign API."""
response = self._make_request(user_id).unwrap()
return self._parse_json(response)
@safe
def _make_request(self, user_id: int) -> requests.Response:
response = requests.get('/api/users/{0}'.format(user_id))
response.raise_for_status()
return response
@safe
def _parse_json(self, response: requests.Response) -> 'UserProfile':
return response.json()
Now we have a clean and a safe way to express our business need. We start from making a request, that might fail at any moment.
Now, instead of returning a regular value it returns a wrapped value inside a special container thanks to the @safe decorator.
It will return Success[Response] or Failure[Exception]. And will never throw this exception at us.
When we will need raw value, we can use .unwrap()
method to get it.
If the result is Failure[Exception]
we will actually raise an exception at this point.
But it is safe to use .unwrap()
inside
@pipeline
functions.
Because it will catch this exception
and wrap it inside a new Failure[Exception]
!
And we can clearly see all result patterns that might happen in this particular case:
Success[UserProfile]
Failure[HttpException]
Failure[JsonDecodeException]
And we can work with each of them precisely.
It is a good practice to create Enum
classes or Union
types
with a list of all the possible errors.
But is that all we can improve?
Let’s look at FetchUserProfile
from another angle.
All its methods look like regular ones:
it is impossible to tell whether they are pure or impure from the first sight.
It leads to a very important consequence: we start to mix pure and impure code together. We should not do that!
When these two concepts are mixed we suffer really bad when testing or reusing it. Almost everything should be pure by default. And we should explicitly mark impure parts of the program.
Let’s refactor it to make our IO explicit!
import requests
from returns.io import IO, impure
from returns.result import Result, pipeline, safe
class FetchUserProfile(object):
"""Single responsibility callable object that fetches user profile."""
@pipeline
def __call__(self, user_id: int) -> Result[IO['UserProfile'], Exception]]:
"""Fetches UserProfile dict from foreign API."""
response = self._make_request(user_id).unwrap()
return self._parse_json(response)
@safe
@impure
def _make_request(self, user_id: int) -> requests.Response:
response = requests.get('/api/users/{0}'.format(user_id))
response.raise_for_status()
return response
@safe
def _parse_json(
self,
io_response: IO[requests.Response],
) -> IO['UserProfile']:
return io_response.map(lambda response: response.json())
Now we have explicit markers where the IO
did happen
and these markers cannot be removed.
Whenever we access FetchUserProfile
we now know
that it does IO
and might fail.
So, we act accordingly!
Want more? Go to the docs! Or read these articles:
Container is a concept that allows you to write code without traditional error handling while maintaining the execution context.
We will show you its 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.
State evolution.¶
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.
Railway oriented programming.¶
We use two methods to create new containers from the previous one.
bind
and map
.
The difference is simple:
map
works with functions that return regular values
bind
works with functions that return other containers
Container.bind
is used to literally bind two different containers together.
from returns.result import Result, Success
def make_http_call(user_id: int) -> Result[int, str]:
...
result = Success(1).bind(make_http_call)
# => Will be equal to either Success[int] or Failure[str]
So, the rule is: whenever you have some impure functions, it should return a container type instead.
And we use Container.map
to use containers with pure functions.
from returns.result import Success
def double(state: int) -> int:
return state * 2
result = Success(1).map(double)
# => Will be equal to Success(2)
Note:
All containers support these methods.
We also support two special methods to work with “failed”
types like Failure
and Nothing
:
Container.fix
is the opposite of map
method
that works only when container is in failed state
Container.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
def double(state: int) -> float:
return state * 2.0
Failure(1).fix(double)
# => Will be equal to Success(2.0)
rescue
can return any container type you want.
It can also fix your flow and get on the successful track again:
from returns.result import Result, Failure, Success
def fix(state: Exception) -> Result[int, Exception]:
if isinstance(state, ZeroDivisionError):
return Success(0)
return Failure(state)
Failure(ZeroDivisionError).rescue(fix)
# => Will be equal to Success(0)
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:
Container.value_or
returns a value if it is possible, returns default_value
otherwise
Container.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.
For failing containers you can
use Container.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.
However, this is still good old python
type system,
and it has its drawbacks.
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.
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.
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.
is_succesful
is used to
tell whether or not your result is a success.
We treat only treat types that does not throw as a successful ones,
basically: Success
.
from returns.result import Success, Failure, is_successful
is_successful(Success(1))
# => True
is_successful(Failure('text'))
# => False
What is a pipeline
?
It is a more user-friendly syntax to work with containers
that support both async and regular functions.
Consider this task. We were asked to create a method that will connect together a simple pipeline of three steps:
We validate passed username
and email
We create a new Account
with this data, if it does not exists
We create a new User
associated with the Account
And we know that this pipeline can fail in several places:
Wrong username
or email
might be passed, so the validation will fail
Account
with this username
or email
might already exist
User
creation might fail as well,
since it also makes an HTTP
request to another micro-service deep inside
Here’s the code to illustrate the task.
from returns.result import Result, Success, Failure, pipeline
class CreateAccountAndUser(object):
"""Creates new Account-User pair."""
# TODO: we need to create a pipeline of these methods somehow...
# Protected methods
def _validate_user(
self, username: str, email: str,
) -> Result['UserSchema', str]:
"""Returns an UserSchema for valid input, otherwise a Failure."""
def _create_account(
self, user_schema: 'UserSchema',
) -> Result['Account', str]:
"""Creates an Account for valid UserSchema's. Or returns a Failure."""
def _create_user(
self, account: 'Account',
) -> Result['User', str]:
"""Create an User instance. If user already exists returns Failure."""
We can implement this feature using a traditional bind
method.
class CreateAccountAndUser(object):
"""Creates new Account-User pair."""
def __call__(self, username: str, email: str) -> Result['User', str]:
"""Can return a Success(user) or Failure(str_reason)."""
return self._validate_user(username, email).bind(
self._create_account,
).bind(
self._create_user,
)
# Protected methods
# ...
And this will work without any problems. But, is it easy to read a code like this? No, it is not.
What alternative we can provide? @pipeline
!
And here’s how we can refactor previous version to be more clear.
class CreateAccountAndUser(object):
"""Creates new Account-User pair."""
@pipeline
def __call__(self, username: str, email: str) -> Result['User', str]:
"""Can return a Success(user) or Failure(str_reason)."""
user_schema = self._validate_user(username, email).unwrap()
account = self._create_account(user_schema).unwrap()
return self._create_user(account)
# Protected methods
# ...
Let’s see how this new .unwrap()
method works:
if you result is Success
it will return its inner value
if your result is Failure
it will raise a UnwrapFailedError
And that’s where @pipeline
decorator becomes in handy.
It will catch any UnwrapFailedError
during the pipeline
and then return a simple Failure
result.
Pipeline execution.¶
See, do notation allows you to write simple yet powerful pipelines with multiple and complex steps. And at the same time the produced code is simple and readable.
And that’s it!
safe
is used to convert
regular functions that can throw exceptions to functions
that return Result
type.
Supports both async and regular functions.
from returns.result import safe
@safe
def divide(number: int) -> float:
return number / number
divide(1)
# => Success(1.0)
divide(0)
# => Failure(ZeroDivisionError)
There’s one limitation in typing that we are facing right now due to mypy issue:
from returns.result import safe
@safe
def function(param: int) -> int:
return param
reveal_type(function)
# Actual => def (*Any, **Any) -> builtins.int
# Expected => def (int) -> builtins.int
This effect can be reduced with the help of Design by Contract with these implementations:
Result
(inner_value)[source]¶Bases: returns.primitives.container.GenericContainerTwoSlots
Base class for Failure and Success.
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()
.
rescue
(function)[source]¶Applies ‘function’ to the result of a previous calculation.
And returns a new container.
Works for containers that represent failure.
Is the opposite of bind()
.
value_or
(default_value)[source]¶Forces to unwrap value from container or return a default.
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-container) argument and return a non-container 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-container) argument and return a non-container result.
is_successful
(container)[source]¶Determins if a container was successful or not.
We treat container that raise UnwrapFailedError
on .unwrap()
not successful.
IO
is ugly.
Why? Let me illustrate it with the example.
Imagine we have this beautiful pure function:
def can_book_seats(
number_of_seats: int,
reservation: 'Reservation',
) -> bool:
return reservation.capacity >= number_of_seats + reservation.booked
What’s good about it? We can test it easily. Even without setting up any testing framework, simple doctests will be enough.
This code is beautiful, because it is simple.
We can later use its result to notify users about their booking request:
def notify_user_about_booking_result(is_successful: bool) -> 'MessageID':
...
notify_user_about_booking_result(is_successful) # works just fine!
But, imagine that our requirements had changed. And now we have to grab the number of already booked tickets from some other provider and fetch the maximum capacity from the database:
import requests
import db
def can_book_seats(
number_of_seats: int,
place_id: int,
) -> bool:
capacity = db.get_place_capacity(place_id) # sql query
booked = requests('https://partner.com/api').json()['booked'] # http req
return capacity >= number_of_seats + booked
Now testing this code will become a nightmare! It will require to setup:
real database and tables
fixture data
requests
mocks for different outcomes
Our complexity has sky-rocketed!
And the most annoying part is that all other functions
that call can_book_seats
now also have to do the same setup.
It seams like IO
is indelible mark.
And at some point it time we will start to mix pure and impure code together.
Well, our IO
mark is indeed indelible and should be respected.
Once you have an IO
operation you can mark it appropriately.
And it infects all other functions that call it.
And impurity becomes explicit:
import requests
import db
from returns.io import IO
def can_book_seats(
number_of_seats: int,
place_id: int,
) -> IO[bool]:
capacity = db.get_place_capacity(place_id) # sql query
booked = requests('https://partner.com/api').json()['booked']
return IO(capacity >= number_of_seats + booked)
Now this function returns IO[bool]
instead of a regular bool
.
It means, that it cannot be used where regular bool
can be:
def notify_user_about_booking_result(is_successful: bool) -> 'MessageID':
...
is_successful: IO[bool] = can_book_seats(number_of_seats, place_id)
notify_user_about_booking_result(is_successful) # Boom!
# => Argument 1 has incompatible type "IO[bool]"; expected "bool"
See? It is now impossible for a pure function to use IO[bool]
.
It is impossible to unwrap or get a value from this container.
Once it is marked as IO
it will never return to the pure state.
Well, there’s a hack actually:
unsafe_perform_io
It also needs to be explicitly mapped to produce new IO
result:
message_id: IO['MessageID'] = can_book_seats(
number_of_seats,
place_id,
).map(
notify_user_about_booking_result,
)
Or it can be annotated to work with impure results:
def notify_user_about_booking_result(
is_successful: IO[bool],
) -> IO['MessageID']:
...
is_successful: IO[bool] = can_book_seats(number_of_seats, place_id)
notify_user_about_booking_result(is_successful) # Works!
Now, all our impurity is explicit. We can track it, we can fight it, we can design it better. By saying that, it is assumed that you have a functional core and imperative shell.
We also have this handy decorator to help you with the existing impure things in Python:
from returns.io import impure
name: IO[str] = impure(input)('What is your name?')
There’s one limitation in typing that we are facing right now due to mypy issue.
IO
(inner_value)[source]¶Bases: returns.primitives.container.GenericContainerOneSlot
Explicit marker for impure function results.
We call it “marker” since once it is marked, it cannot be unmarked.
IO
is also a container.
But, it is different in a way
that it cannot be unwrapped / rescued / fixed.
There’s no way to directly get its internal value.
Sometimes you really need to get the raw value. For example:
def index_view(request, user_id):
user: IO[User] = get_user(user_id)
return render('index.html', { user: user }) # ???
In this case your web-framework will not render your user correctly.
Since it does not expect it to be wrapped inside IO
containers.
What to do? Use unsafe_perform_io
:
from returns.unsafe import unsafe_perform_io
def index_view(request, user_id):
user: IO[User] = get_user(user_id)
return render('index.html', { user: unsafe_perform_io(user) }) # Ok
We need it as an escape and compatibility mechanism for our imperative shell.
It is recommended
to use import-linter
to restrict imports from returns.unsafe
expect the top-level modules.
Inspired by Haskell’s unsafePerformIO
unsafe_perform_io
(wrapped_in_io)[source]¶Compatibility utility and escape mechanism from IO
world.
Just unwraps the internal value
from IO
container.
Should be used with caution!
Since it might be overused by tired developers.
It is recommended to have only one place (module / file) in your program where you allow unsafe operations.
We recommend to use import-linter
to enforce this rule:
We feature several helper functions to make your developer experience better.
We also ship an utility function to compose two different functions together.
from returns.functions import compose
bool_after_int = compose(int, bool)
bool_after_int('1') # => True
bool_after_int('0') # => False
Composition is also type-safe. The only limitation is that we only support functions with one argument and one return to be composed.
Only works with regular functions (not async).
Sometimes you really want to reraise an exception from Failure[Exception]
due to some existing API (or a dirty hack).
We allow you to do that with ease!
from returns.functions import raise_exception
class CreateAccountAndUser(object):
"""Creates new Account-User pair."""
@pipeline
def __call__(self, username: str) -> ...:
"""Imagine, that you need to reraise ValidationErrors due to API."""
user_schema = self._validate_user(
username,
).fix(
# What happens here is interesting, since you do not let your
# unwrap to fail with UnwrapFailedError, but instead
# allows you to reraise a wrapped exception.
# In this case `ValidationError()` will be thrown
# before `UnwrapFailedError`
raise_exception,
).unwrap()
def _validate_user(
self, username: str,
) -> Result['User', ValidationError]:
...
Use this with caution. We try to remove exceptions from our code base. Original proposal is here.
compose
(first, second)[source]¶Allows function composition.
Works as: second . first
You can read it as “second after first”.
We can only compose functions with one argument and one return.
We follow Semantic Versions since the 0.1.0
release.
Adds IO
marker
Adds unsafe
module with unsafe functions
Changes how functions are located inside the project
Fixes container type in @pipeline
Now is_successful
is public
Now raise_exception
is public
Changes how str()
function works for container types
Total rename to “container” in the source code
safe
and pipeline
now supports asyncio
is_successful
now returns Literal
types if possible
Adds compose
helper function
Adds public API to import returns
Adds raise_exception
helper function
Adds full traceback to .unwrap()
Updates multiple dev-dependencies, including mypy
Now search in the docs is working again
Relicenses this project to BSD
Fixes copyright notice in the docs
Moves all types to .pyi
files
Renames all classes according to new naming pattern
HUGE improvement of types
Renames fmap
to map
Renames do_notation
to pipeline
, moves it to functions.py
Renames ebind
to rescue
Renames efmap
to fix
Renames Monad
to Container
Removes Maybe
monad, since typing does not have NonNullable
type
returns
¶The project is renamed to returns
and moved to dry-python
org.
Adds .pyi
files for all modules,
to enable mypy
support for 3rd party users
Adds Maybe
monad
Adds immutability and __slots__
to all monads
Adds methods to work with failures
Adds safe
decorator to convert exceptions to Result
monad
Adds is_successful()
function to detect if your result is a success
Adds failure()
method to unwrap values from failed monads
Changes the type of .bind
method for Success
monad
Changes how equality works, so now Failure(1) != Success(1)
Changes how new instances created on unused methods
Improves docs
Changes how PyPI
renders package’s page
Improves README
with new badges and installation steps
Initial release. Featuring only Result
and do_notation
.