Make your functions return something meaningful, typed, and safe!
Project description
Make your functions return something meaningful, typed, and safe!
Features
- Provides a bunch of primitives to write declarative business logic
- Enforces Railway Oriented Programming
- Fully typed with annotations and checked with
mypy
, PEP561 compatible - Pythonic and pleasant to write and to read (!)
- Support functions and coroutines, framework agnostic
Installation
pip install returns
Make sure you know how to get started, check out our docs!
Why?
Consider this code that you can find in any python
project.
Straight-forward approach
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.
Hidden problems
Let's have a look at the exact same code, but with the all hidden problems explained.
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))
# What if we try to find user that does not exist?
# Or network will go down? Or the server will return 500?
# In this case the next line will fail with an exception.
# We need to handle all possible errors in this function
# and do not return corrupt data to consumers.
response.raise_for_status()
# What if we have received invalid JSON?
# Next line will raise an exception!
return response.json()
Now, all (probably all?) problems are clear. How can we be sure that this function will be safe to use inside our complex business logic?
We really can not be sure!
We will have to create lots of try
and except
cases
just to catch the expected exceptions.
Our code will become complex and unreadable with all this mess!
Pipeline example
import requests
from returns.functions import pipeline, safe
from returns.result import Result
class FetchUserProfile(object):
"""Single responsibility callable object that fetches user profile."""
#: You can later use dependency injection to replace `requests`
#: with any other http library (or even a custom service).
_http = requests
@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 = self._http.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.
What more? Go to the docs!
License
MIT.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file returns-0.6.0.tar.gz
.
File metadata
- Download URL: returns-0.6.0.tar.gz
- Upload date:
- Size: 10.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/0.12.11 CPython/3.7.3 Darwin/18.2.0
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 3ee82e04d15a201a41a069c95ffad225fbc59bf432fa16c59955282dc9c8a1fe |
|
MD5 | 6b7da9d0ab0f010f04770c19cacd6307 |
|
BLAKE2b-256 | 8841fb3ee0d0b5e11a0389555944c37a0c559fea82a4e6689728a6adcddc72e0 |
File details
Details for the file returns-0.6.0-py3-none-any.whl
.
File metadata
- Download URL: returns-0.6.0-py3-none-any.whl
- Upload date:
- Size: 25.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/0.12.11 CPython/3.7.3 Darwin/18.2.0
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | b77d66d6ffe8846bda087961e01a32daa760f18e2d6642644d7dd8e9db289356 |
|
MD5 | 8edb4bd11d697bebdbe6dba0820a6485 |
|
BLAKE2b-256 | a59f9fd2d3bfbd35a2ce81b5032e5fdee14268111cc5fac42e740b05715a002d |