Helper functions

We feature several helper functions to make your developer experience better.


We also ship an utility function to compose two different functions together.

from returns.functions import compose

bool_after_int = compose(int, bool)
bool_after_int('1')  # => True
bool_after_int('0')  # => False

Composition is also type-safe. The only limitation is that we only support functions with one argument and one return to be composed.

Only works with regular functions (not async).


Sometimes you really want to reraise an exception from Failure[Exception] due to some existing API (or a dirty hack).

We allow you to do that with ease!

from returns.functions import raise_exception

class CreateAccountAndUser(object):
    """Creates new Account-User pair."""

    def __call__(self, username: str) -> ...:
        """Imagine, that you need to reraise ValidationErrors due to API."""
        return self._validate_user(
            # TODO: change in #84 to `.map_failure()`
            # What happens here is interesting, since you do not let your
            # unwrap to fail with UnwrapFailedError, but instead
            # allows you to reraise a wrapped exception.
            # In this case `ValidationError()` will be thrown
            # before `UnwrapFailedError`

    def _validate_user(
        self, username: str,
    ) -> Result['User', ValidationError]:

Use this with caution. We try to remove exceptions from our code base. Original proposal is here.

API Reference

compose(first, second)[source]

Allows function composition.

Works as: second . first You can read it as “second after first”.

from returns.functions import compose

logged_int = compose(int, print)('123')
# => returns: 123
# => prints: 123

We can only compose functions with one argument and one return. Type checked.

Return type

Callable[[~_FirstType], ~_ThirdType]


Helper function to raise exceptions as a function.

It might be required as a compatibility tool for existing APIs.

That’s how it can be used:

from returns.functions import raise_exception

# Some operation result:
user: Failure[UserDoesNotExistError]

# Here we unwrap internal exception and raise it:


Return type