Skip to main content

Make your functions return something meaningful, typed, and safe!

Project description

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 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

Installation

pip install returns

Make sure you know how to get started, check out our docs!

Contents

Result container

Please, make sure that you are also aware of Railway Oriented Programming.

Straight-forward approach

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.

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.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.

IO marker

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.

Explicit IO

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!

More!

Want more? Go to the docs! Or read these articles:

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

returns-0.7.0.tar.gz (12.5 kB view details)

Uploaded Source

Built Distribution

returns-0.7.0-py3-none-any.whl (29.6 kB view details)

Uploaded Python 3

File details

Details for the file returns-0.7.0.tar.gz.

File metadata

  • Download URL: returns-0.7.0.tar.gz
  • Upload date:
  • Size: 12.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

Hashes for returns-0.7.0.tar.gz
Algorithm Hash digest
SHA256 70e8e02f142ad23d8d9289317aeef461fdaa4bda451dce08548a60268985a055
MD5 58eb4e31e21cc83328584139b4b38490
BLAKE2b-256 c7be6c76a324f61c99fa58b268136d8a69c9490179dc4c55c4f9fc4633f093e5

See more details on using hashes here.

File details

Details for the file returns-0.7.0-py3-none-any.whl.

File metadata

  • Download URL: returns-0.7.0-py3-none-any.whl
  • Upload date:
  • Size: 29.6 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

Hashes for returns-0.7.0-py3-none-any.whl
Algorithm Hash digest
SHA256 4ae24494066f50a272c979a3a562e7010e1c13bc3251c54cfaa3071015707177
MD5 4b60ffc64e60ad454cb1779483a1c428
BLAKE2b-256 c3f98a54e06146b8f05a2659780241969424d1203c60d2d3870ea7ce6078b902

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page