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 (!)
- WIP:
asyncio
support
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.5.0.tar.gz
.
File metadata
- Download URL: returns-0.5.0.tar.gz
- Upload date:
- Size: 10.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/0.12.11 CPython/3.6.6 Darwin/18.2.0
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | bd920157db625f632eacc2b9e32d089367a22b4ebee69f59538fffe0f1ea2df6 |
|
MD5 | 03a72ae4b07ed1320ed7782d1c79a2fd |
|
BLAKE2b-256 | 81177c3bb77baa1dc114290db5055d21cebf814ce743731c591a9708609a9261 |
File details
Details for the file returns-0.5.0-py3-none-any.whl
.
File metadata
- Download URL: returns-0.5.0-py3-none-any.whl
- Upload date:
- Size: 23.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/0.12.11 CPython/3.6.6 Darwin/18.2.0
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 843a60a9da47fb414786046da78103ea4903b51faaf93a9431ef1e607dfdb45a |
|
MD5 | 6942c4f417863de26bd7648bb09d7038 |
|
BLAKE2b-256 | aa72e29f17e86c0bfdf80608db2c6bac3adb244390f3d1538e798bb907b94338 |