Make your functions return something meaningful, typed, and safe!
Project description
returns
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
, allowing you to write type-safe code as well, PEP561 compatible - Pythonic and pleasant to write and to read (!)
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.4.0.tar.gz
.
File metadata
- Download URL: returns-0.4.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 | 1f276bcd3b9ae4105fa5c10b99552196f6f7679c722ba7a2bd0f30fe70ffd73a |
|
MD5 | 2703ac484c2f3c1e53c27ac3f6c3e842 |
|
BLAKE2b-256 | 0c0a466461214aec2f673d3c859cffd4ccf4069d227a555bbe97a7d1a7fb2509 |
Provenance
File details
Details for the file returns-0.4.0-py3-none-any.whl
.
File metadata
- Download URL: returns-0.4.0-py3-none-any.whl
- Upload date:
- Size: 21.9 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 | 7684bb25443011fa3d8ac01d72d5d341c96efccd4df689360b17450d86bf40fc |
|
MD5 | b218f1bc80a90bf43136f922d384c80b |
|
BLAKE2b-256 | c72ba87d557db9186f77381ab178baf14fcc7e435924aab1a157b03cbd150a8a |