Make your functions return something meaningful, typed, and safe!
Branch: master
Clone or download
Latest commit 9739f27 Feb 19, 2019
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
docs Merge pull request #36 from dry-python/dependabot/pip/docs/sphinx-typ… Feb 18, 2019
returns
tests Fixes CI Feb 18, 2019
.editorconfig Initial pyi stubs are created Feb 2, 2019
.gitignore Initial commit Jan 26, 2019
.readthedocs.yml Docs started Jan 28, 2019
.travis.yml Fixes mypy Feb 2, 2019
CHANGELOG.md Adds searchbox, updates deps, closes #3 Feb 18, 2019
CONTRIBUTING.md Working on .pyi types Feb 2, 2019
LICENSE Relicensed to BSD Feb 8, 2019
README.md Update README.md Feb 8, 2019
poetry.lock Bump pytest from 4.2.1 to 4.3.0 Feb 19, 2019
pyproject.toml Bump pytest from 4.2.1 to 4.3.0 Feb 19, 2019
setup.cfg Adds searchbox, updates deps, closes #3 Feb 18, 2019

README.md

Returns logo


Build Status Coverage Status Documentation Status Python Version wemake-python-styleguide


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.