



returns 0.22.0 documentation

[returns](#) 

[returns](#)Make your functions return something meaningful, typed, and safe!

* [Quickstart](index.html#document-pages/quickstart)

Userguide

* [Container: the concept](index.html#document-pages/container)

* [Railway oriented programming](index.html#document-pages/railway)

* [Higher Kinded Types](index.html#document-pages/hkt)

* [Interfaces](index.html#document-pages/interfaces)

Containers

* [Maybe](index.html#document-pages/maybe)

* [Result](index.html#document-pages/result)

* [IO](index.html#document-pages/io)

* [Future](index.html#document-pages/future)

* [Context](index.html#document-pages/context)

* [Create your own container](index.html#document-pages/create-your-own-container)

Composition helpers

* [Pipelines](index.html#document-pages/pipeline)

* [Converters](index.html#document-pages/converters)

* [Pointfree](index.html#document-pages/pointfree)

* [Methods](index.html#document-pages/methods)

* [Do Notation](index.html#document-pages/do-notation)

* [Helper functions](index.html#document-pages/functions)

* [Curry](index.html#document-pages/curry)

* [Trampolines](index.html#document-pages/trampolines)

* [Primitive types](index.html#document-pages/types)

Integration

* [Development tooling](index.html#document-pages/development)

* [mypy plugin](index.html#document-pages/contrib/mypy_plugins)

* [pytest plugin](index.html#document-pages/contrib/pytest_plugins)

* [hypothesis plugin](index.html#document-pages/contrib/hypothesis_plugins)

Changelog

* [Version history](index.html#document-pages/changelog)

[**-**stars

 

**-**forks](https://github.com/dry-python/returns)

Go

### 

Links

* [GitHub](https://github.com/dry-python/returns)

* [PyPI](https://pypi.python.org/pypi/returns)

* [Travis CI](https://travis-ci.com/dry-python/returns)

* [Coverage](https://coveralls.io/github/dry-python/returns?branch=master)

[![Returns logo](https://raw.githubusercontent.com/dry-python/brand/master/logo/returns_white-outline.png)](https://github.com/dry-python/returns)

---

[![Build Status](https://github.com/dry-python/returns/workflows/test/badge.svg?branch=master&event=push)](https://github.com/dry-python/returns/actions?query=workflow%3Atest)

[![codecov](https://codecov.io/gh/dry-python/returns/branch/master/graph/badge.svg)](https://codecov.io/gh/dry-python/returns)

[![Documentation Status](https://readthedocs.org/projects/returns/badge/?version=latest)](https://returns.readthedocs.io/en/latest/?badge=latest)

[![Python Version](https://img.shields.io/pypi/pyversions/returns.svg)](https://pypi.org/project/returns/)

[![wemake-python-styleguide](https://img.shields.io/badge/style-wemake-000000.svg)](https://github.com/wemake-services/wemake-python-styleguide)

[![Telegram chat](https://img.shields.io/badge/chat-join-blue?logo=telegram)](https://t.me/drypython)

---

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

Features[¶](#features "Permalink to this heading")

==================================================

* Brings functional programming to Python land

* Provides a bunch of primitives to write declarative business logic

* Enforces better architecture

* Fully typed with annotations and checked with `mypy`, [PEP561 compatible](https://www.python.org/dev/peps/pep-0561/)

* Adds emulated Higher Kinded Types support

* Provides type-safe interfaces to create your own data-types with enforced laws

* Has a bunch of helpers for better composition

* Pythonic and pleasant to write and to read 🐍

* Support functions and coroutines, framework agnostic

* Easy to start: has lots of docs, tests, and tutorials

[Quickstart](https://returns.readthedocs.io/en/latest/pages/quickstart.html) right now!

Installation[¶](#installation "Permalink to this heading")

==========================================================

```

pip install returns

```

You can also install `returns` with the latest supported `mypy` version:

```

pip install returns[compatible-mypy]

```

You would also need to configure our ``mypy` plugin <<https://returns.readthedocs.io/en/latest/pages/contrib/mypy_plugins.html>>`\_:

```

# In setup.cfg or mypy.ini:

[mypy]

plugins =

 returns.contrib.mypy.returns\_plugin

```

or:

```

[tool.mypy]

plugins = ["returns.contrib.mypy.returns\_plugin"]

```

We also recommend to use the same `mypy` settings [we use](https://github.com/wemake-services/wemake-python-styleguide/blob/master/styles/mypy.toml).

Make sure you know how to get started, [check out our docs](https://returns.readthedocs.io/en/latest/)!

[Try our demo](https://repl.it/@sobolevn/returns#ex.py).

Contents[¶](#contents "Permalink to this heading")

==================================================

* [Maybe container](#maybe-container) that allows you to write `None`-free code

* [RequiresContext container](#requirescontext-container) that allows you to use typed functional dependency injection

* [Result container](#result-container) that let’s you to get rid of exceptions

* [IO container](#io-container) and [IOResult](#troublesome-io) that marks all impure operations and structures them

* [Future container](#future-container) and [FutureResult](#async-code-without-exceptions) to work with `async` code

* [Write your own container!](https://returns.readthedocs.io/en/latest/pages/create-your-own-container.html) You would still have all the features for your own types (including full existing code reuse and type-safety)

Maybe container[¶](#id1 "Permalink to this heading")

====================================================

`None` is called the [worst mistake in the history of Computer Science](https://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare/).

So, what can we do to check for `None` in our programs?

You can use builtin [Optional](https://mypy.readthedocs.io/en/stable/kinds_of_types.html#optional-types-and-the-none-type) type

and write a lot of `if some is not None:` conditions.

But, **having ``null`` checks here and there makes your code unreadable**.

```

user: Optional[User]

discount\_program: Optional['DiscountProgram'] = None

if user is not None:

     balance = user.get\_balance()

     if balance is not None:

         credit = balance.credit\_amount()

         if credit is not None and credit > 0:

             discount\_program = choose\_discount(credit)

```

Or you can use

[Maybe](https://returns.readthedocs.io/en/latest/pages/maybe.html) container!

It consists of `Some` and `Nothing` types,

representing existing state and empty (instead of `None`) state respectively.

```

from typing import Optional

from returns.maybe import Maybe, maybe

@maybe  # decorator to convert existing Optional[int] to Maybe[int]

def bad\_function() -> Optional[int]:

    ...

maybe\_number: Maybe[float] = bad\_function().bind\_optional(

    lambda number: number / 2,

)

# => Maybe will return Some[float] only if there's a non-None value

# Otherwise, will return Nothing

```

You can be sure that `.bind\_optional()` method won’t be called for `Nothing`.

Forget about `None`-related errors forever!

We can also bind a `Optional`-returning function over a container.

To achieve this, we are going to use `.bind\_optional` method.

And here’s how your initial refactored code will look:

```

user: Optional[User]

# Type hint here is optional, it only helps the reader here:

discount\_program: Maybe['DiscountProgram'] = Maybe.from\_optional(

    user,

).bind\_optional(  # This won't be called if `user is None`

    lambda real\_user: real\_user.get\_balance(),

).bind\_optional(  # This won't be called if `real\_user.get\_balance()` is None

    lambda balance: balance.credit\_amount(),

).bind\_optional(  # And so on!

    lambda credit: choose\_discount(credit) if credit > 0 else None,

)

```

Much better, isn’t it?

RequiresContext container[¶](#id2 "Permalink to this heading")

==============================================================

Many developers do use some kind of dependency injection in Python.

And usually it is based on the idea

that there’s some kind of a container and assembly process.

Functional approach is much simpler!

Imagine that you have a `django` based game, where you award users with points for each guessed letter in a word (unguessed letters are marked as `'.'`):

```

from django.http import HttpRequest, HttpResponse

from words\_app.logic import calculate\_points

def view(request: HttpRequest) -> HttpResponse:

    user\_word: str = request.POST['word']  # just an example

    points = calculate\_points(user\_word)

    ...  # later you show the result to user somehow

# Somewhere in your `words\_app/logic.py`:

def calculate\_points(word: str) -> int:

    guessed\_letters\_count = len([letter for letter in word if letter != '.'])

    return \_award\_points\_for\_letters(guessed\_letters\_count)

def \_award\_points\_for\_letters(guessed: int) -> int:

    return 0 if guessed < 5 else guessed  # minimum 6 points possible!

```

Awesome! It works, users are happy, your logic is pure and awesome.

But, later you decide to make the game more fun:

let’s make the minimal accountable letters threshold

configurable for an extra challenge.

You can just do it directly:

```

def \_award\_points\_for\_letters(guessed: int, threshold: int) -> int:

    return 0 if guessed < threshold else guessed

```

The problem is that `\_award\_points\_for\_letters` is deeply nested.

And then you have to pass `threshold` through the whole callstack,

including `calculate\_points` and all other functions that might be on the way.

All of them will have to accept `threshold` as a parameter!

This is not useful at all!

Large code bases will struggle a lot from this change.

Ok, you can directly use `django.settings` (or similar)

in your `\_award\_points\_for\_letters` function.

And **ruin your pure logic with framework specific details**. That’s ugly!

Or you can use `RequiresContext` container. Let’s see how our code changes:

```

from django.conf import settings

from django.http import HttpRequest, HttpResponse

from words\_app.logic import calculate\_points

def view(request: HttpRequest) -> HttpResponse:

    user\_word: str = request.POST['word']  # just an example

    points = calculate\_points(user\_words)(settings)  # passing the dependencies

    ...  # later you show the result to user somehow

# Somewhere in your `words\_app/logic.py`:

from typing import Protocol

from returns.context import RequiresContext

class \_Deps(Protocol):  # we rely on abstractions, not direct values or types

    WORD\_THRESHOLD: int

def calculate\_points(word: str) -> RequiresContext[int, \_Deps]:

    guessed\_letters\_count = len([letter for letter in word if letter != '.'])

    return \_award\_points\_for\_letters(guessed\_letters\_count)

def \_award\_points\_for\_letters(guessed: int) -> RequiresContext[int, \_Deps]:

    return RequiresContext(

        lambda deps: 0 if guessed < deps.WORD\_THRESHOLD else guessed,

    )

```

And now you can pass your dependencies in a really direct and explicit way.

And have the type-safety to check what you pass to cover your back.

Check out [RequiresContext](https://returns.readthedocs.io/en/latest/pages/context.html) docs for more. There you will learn how to make `'.'` also configurable.

We also have [RequiresContextResult](https://returns.readthedocs.io/en/latest/pages/context.html#requirescontextresult-container)

for context-related operations that might fail. And also [RequiresContextIOResult](https://returns.readthedocs.io/en/latest/pages/context.html#requirescontextioresult-container) and [RequiresContextFutureResult](https://returns.readthedocs.io/en/latest/pages/context.html#requirescontextfutureresult-container).

Result container[¶](#id3 "Permalink to this heading")

=====================================================

Please, make sure that you are also aware of

[Railway Oriented Programming](https://fsharpforfunandprofit.com/rop/).

Straight-forward approach[¶](#straight-forward-approach "Permalink to this heading")

------------------------------------------------------------------------------------

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 it not?

It also seems like a pretty straightforward 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[¶](#hidden-problems "Permalink to this heading")

----------------------------------------------------------------

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

Or we can go with the top level `except Exception:` case

to catch literally everything.

And this way we would end up with catching unwanted ones.

This approach can hide serious problems from us for a long time.

Pipe example[¶](#pipe-example "Permalink to this heading")

----------------------------------------------------------

```

import requests

from returns.result import Result, safe

from returns.pipeline import flow

from returns.pointfree import bind

def fetch\_user\_profile(user\_id: int) -> Result['UserProfile', Exception]:

 """Fetches `UserProfile` TypedDict from foreign API."""

    return flow(

        user\_id,

        \_make\_request,

        bind(\_parse\_json),

    )

@safe

def \_make\_request(user\_id: int) -> requests.Response:

    # TODO: we are not yet done with this example, read more about `IO`:

    response = requests.get('/api/users/{0}'.format(user\_id))

    response.raise\_for\_status()

    return response

@safe

def \_parse\_json(response: requests.Response) -> 'UserProfile':

    return response.json()

```

Now we have a clean and a safe and declarative way

to express our business needs:

* We start from making a request, that might fail at any moment,

* Then parsing the response if the request was successful,

* And then return the result.

Now, instead of returning regular values

we return values wrapped inside a special container

thanks to the

[@safe](https://returns.readthedocs.io/en/latest/pages/result.html#safe)

decorator. It will return [Success[YourType] or Failure[Exception]](https://returns.readthedocs.io/en/latest/pages/result.html).

And will never throw exception at us!

We also use [flow](https://returns.readthedocs.io/en/latest/pages/pipeline.html#flow)

and [bind](https://returns.readthedocs.io/en/latest/pages/pointfree.html#bind)

functions for handy and declarative composition.

This way we can be sure that our code won’t break in

random places due to some implicit exception.

Now we control all parts and are prepared for the explicit errors.

We are not yet done with this example,

let’s continue to improve it in the next chapter.

IO container[¶](#id4 "Permalink to this heading")

=================================================

Let’s look at our example from another angle.

All its functions look like regular ones:

it is impossible to tell whether they are [pure](https://en.wikipedia.org/wiki/Pure_function)

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.

That’s why we have created `IO` container

to mark impure functions that never fail.

These impure functions use `random`, current datetime, environment, or console:

```

import random

import datetime as dt

from returns.io import IO

def get\_random\_number() -> IO[int]:  # or use `@impure` decorator

    return IO(random.randint(1, 10))  # isn't pure, because random

now: Callable[[], IO[dt.datetime]] = impure(dt.datetime.now)

@impure

def return\_and\_show\_next\_number(previous: int) -> int:

    next\_number = previous + 1

    print(next\_number)  # isn't pure, because does IO

    return next\_number

```

Now we can clearly see which functions are pure and which ones are impure.

This helps us a lot in building large applications, unit testing you code,

and composing business logic together.

Troublesome IO[¶](#troublesome-io "Permalink to this heading")

--------------------------------------------------------------

As it was already said, we use `IO` when we handle functions that do not fail.

What if our function can fail and is impure?

Like `requests.get()` we had earlier in our example.

Then we have to use a special `IOResult` type instead of a regular `Result`.

Let’s find the difference:

* Our `\_parse\_json` function always returns

the same result (hopefully) for the same input:

you can either parse valid `json` or fail on invalid one.

That’s why we return pure `Result`, there’s no `IO` inside

* Our `\_make\_request` function is impure and can fail.

Try to send two similar requests with and without internet connection.

The result will be different for the same input.

That’s why we must use `IOResult` here: it can fail and has `IO`

So, in order to fulfill our requirement and separate pure code from impure one,

we have to refactor our example.

Explicit IO[¶](#explicit-io "Permalink to this heading")

--------------------------------------------------------

Let’s make our [IO](https://returns.readthedocs.io/en/latest/pages/io.html)

explicit!

```

import requests

from returns.io import IOResult, impure\_safe

from returns.result import safe

from returns.pipeline import flow

from returns.pointfree import bind\_result

def fetch\_user\_profile(user\_id: int) -> IOResult['UserProfile', Exception]:

 """Fetches `UserProfile` TypedDict from foreign API."""

    return flow(

        user\_id,

        \_make\_request,

        # before: def (Response) -> UserProfile

        # after safe: def (Response) -> ResultE[UserProfile]

        # after bind\_result: def (IOResultE[Response]) -> IOResultE[UserProfile]

        bind\_result(\_parse\_json),

    )

@impure\_safe

def \_make\_request(user\_id: int) -> requests.Response:

    response = requests.get('/api/users/{0}'.format(user\_id))

    response.raise\_for\_status()

    return response

@safe

def \_parse\_json(response: requests.Response) -> 'UserProfile':

    return response.json()

```

And later we can use [unsafe\_perform\_io](https://returns.readthedocs.io/en/latest/pages/io.html#unsafe-perform-io)

somewhere at the top level of our program to get the pure (or “real”) value.

As a result of this refactoring session, we know everything about our code:

* Which parts can fail,

* Which parts are impure,

* How to compose them in a smart, readable, and typesafe manner.

Future container[¶](#id5 "Permalink to this heading")

=====================================================

There are several issues with `async` code in Python:

1. You cannot call `async` function from a sync one

2. Any unexpectedly thrown exception can ruin your whole event loop

3. Ugly composition with lots of `await` statements

`Future` and `FutureResult` containers solve these issues!

Mixing sync and async code[¶](#mixing-sync-and-async-code "Permalink to this heading")

--------------------------------------------------------------------------------------

The main feature of [Future](https://returns.readthedocs.io/en/latest/pages/future.html)

is that it allows to run async code

while maintaining sync context. Let’s see an example.

Let’s say we have two functions,

the `first` one returns a number and the `second` one increments it:

```

async def first() -> int:

    return 1

def second():  # How can we call `first()` from here?

    return first() + 1  # Boom! Don't do this. We illustrate a problem here.

```

If we try to just run `first()`, we will just create an unawaited coroutine.

It won’t return the value we want.

But, if we would try to run `await first()`,

then we would need to change `second` to be `async`.

And sometimes it is not possible for various reasons.

However, with `Future` we can “pretend” to call async code from sync code:

```

from returns.future import Future

def second() -> Future[int]:

    return Future(first()).map(lambda num: num + 1)

```

Without touching our `first` async function

or making `second` async we have achieved our goal.

Now, our async value is incremented inside a sync function.

However, `Future` still requires to be executed inside a proper eventloop:

```

import anyio  # or asyncio, or any other lib

# We can then pass our `Future` to any library: asyncio, trio, curio.

# And use any event loop: regular, uvloop, even a custom one, etc

assert anyio.run(second().awaitable) == 2

```

As you can see `Future` allows you

to work with async functions from a sync context.

And to mix these two realms together.

Use raw `Future` for operations that cannot fail or raise exceptions.

Pretty much the same logic we had with our `IO` container.

Async code without exceptions[¶](#async-code-without-exceptions "Permalink to this heading")

--------------------------------------------------------------------------------------------

We have already covered how ``Result` <#result-container>`\_ works

for both pure and impure code.

The main idea is: we don’t raise exceptions, we return them.

It is **especially** critical in async code,

because a single exception can ruin

all our coroutines running in a single eventloop.

We have a handy combination of `Future` and `Result` containers: `FutureResult`.

Again, this is exactly like `IOResult`, but for impure async code.

Use it when your `Future` might have problems:

like HTTP requests or filesystem operations.

You can easily turn any wild throwing coroutine into a calm `FutureResult`:

```

import anyio

from returns.future import future\_safe

from returns.io import IOFailure

@future\_safe

async def raising():

    raise ValueError('Not so fast!')

ioresult = anyio.run(raising.awaitable)  # all `Future`s return IO containers

assert ioresult == IOFailure(ValueError('Not so fast!'))  # True

```

Using `FutureResult` will keep your code safe from exceptions.

You can always `await` or execute inside an eventloop any `FutureResult`

to get sync `IOResult` instance to work with it in a sync manner.

Better async composition[¶](#better-async-composition "Permalink to this heading")

----------------------------------------------------------------------------------

Previously, you had to do quite a lot of `await`ing while writing `async` code:

```

async def fetch\_user(user\_id: int) -> 'User':

    ...

async def get\_user\_permissions(user: 'User') -> 'Permissions':

    ...

async def ensure\_allowed(permissions: 'Permissions') -> bool:

    ...

async def main(user\_id: int) -> bool:

    # Also, don't forget to handle all possible errors with `try / except`!

    user = await fetch\_user(user\_id)  # We will await each time we use a coro!

    permissions = await get\_user\_permissions(user)

    return await ensure\_allowed(permissions)

```

Some people are ok with it, but some people don’t like this imperative style.

The problem is that there was no choice.

But now, you can do the same thing in functional style!

With the help of `Future` and `FutureResult` containers:

```

import anyio

from returns.future import FutureResultE, future\_safe

from returns.io import IOSuccess, IOFailure

@future\_safe

async def fetch\_user(user\_id: int) -> 'User':

    ...

@future\_safe

async def get\_user\_permissions(user: 'User') -> 'Permissions':

    ...

@future\_safe

async def ensure\_allowed(permissions: 'Permissions') -> bool:

    ...

def main(user\_id: int) -> FutureResultE[bool]:

    # We can now turn `main` into a sync function, it does not `await` at all.

    # We also don't care about exceptions anymore, they are already handled.

    return fetch\_user(user\_id).bind(get\_user\_permissions).bind(ensure\_allowed)

correct\_user\_id: int  # has required permissions

banned\_user\_id: int  # does not have required permissions

wrong\_user\_id: int  # does not exist

# We can have correct business results:

assert anyio.run(main(correct\_user\_id).awaitable) == IOSuccess(True)

assert anyio.run(main(banned\_user\_id).awaitable) == IOSuccess(False)

# Or we can have errors along the way:

assert anyio.run(main(wrong\_user\_id).awaitable) == IOFailure(

    UserDoesNotExistError(...),

)

```

Or even something really fancy:

```

from returns.pointfree import bind

from returns.pipeline import flow

def main(user\_id: int) -> FutureResultE[bool]:

    return flow(

        fetch\_user(user\_id),

        bind(get\_user\_permissions),

        bind(ensure\_allowed),

    )

```

Later we can also refactor our logical functions to be sync

and to return `FutureResult`.

Lovely, isn’t it?

More![¶](#more "Permalink to this heading")

===========================================

Want more?

[Go to the docs!](https://returns.readthedocs.io)

Or read these articles:

* [Python exceptions considered an anti-pattern](https://sobolevn.me/2019/02/python-exceptions-considered-an-antipattern)

* [Enforcing Single Responsibility Principle in Python](https://sobolevn.me/2019/03/enforcing-srp)

* [Typed functional Dependency Injection in Python](https://sobolevn.me/2020/02/typed-functional-dependency-injection)

* [How Async Should Have Been](https://sobolevn.me/2020/06/how-async-should-have-been)

* [Higher Kinded Types in Python](https://sobolevn.me/2020/10/higher-kinded-types-in-python)

* [Make Tests a Part of Your App](https://sobolevn.me/2021/02/make-tests-a-part-of-your-app)

Do you have an article to submit? Feel free to open a pull request!

Contents[¶](#id6 "Permalink to this heading")

=============================================

Quickstart[¶](#quickstart "Permalink to this heading")

------------------------------------------------------

Starting is really fast!

You can integrate `returns` into any project at any stage.

You can use it fully or partially. With or without types.

`returns` is a very flexible library!

You can even just start using it without any deep theory around this project.

But, you can always address our learning materials

which will unravel all parts of functional programming

with useful examples and simple terms.

### Why[¶](#why "Permalink to this heading")

One of the most frequent questions

Python developers ask: why would we need this?

Basically, the answer is that `returns` provides

useful abstractions that solve some problems every developer has:

1. [`Maybe`](index.html#returns.maybe.Maybe "returns.maybe.Maybe") helps to work with `None` in a type-safe way

2. [`Result`](index.html#returns.result.Result "returns.result.Result") helps

to work with exceptions in a type-safe way

3. [`IO`](index.html#returns.io.IO "returns.io.IO") helps to separate pure code

from impure code to make your architecture better

4. [`Future`](index.html#returns.future.Future "returns.future.Future") helps to write `await` free code

5. [`RequiresContext`](index.html#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext") helps

to inject dependencies in a very readable, explicit, type-safe, and clean way

6. [Pipelines](index.html#pipelines) can be used independently or together with the types above

to create complex, declarative, and type-safe data pipelines

On top of that we provide useful interfaces that allows you

to switch implementation on the fly.

For example, you can write code that works the same way

for sync and async execution flows.

While being fully type-safe at the same time.

And you can write your own primitives that will solve any other problem

you can possible have based on our existing or your custom interfaces.

In other words, `returns` unlocks insane powers

of typed-functional programming to a regular Python developer.

### Installation[¶](#installation "Permalink to this heading")

`returns` is a pure Python library. Install it as usual:

```

pip install returns # or better use poetry

```

### Typechecking and other integrations[¶](#typechecking-and-other-integrations "Permalink to this heading")

This step is optional.

If you use `mypy` for type-checking, than you will need to configure it.

We really recommend using `mypy` with this project though.

Because we have put a lot of efforts into the typing part.

Check out our docs on [mypy](index.html#mypy-plugins).

We also have built-in integrations

with [pytest](index.html#pytest-plugins) and [hypothesis](index.html#hypothesis-plugins).

Also, there is [developer tooling](index.html#development-tooling) you might enjoy.

### Theory[¶](#theory "Permalink to this heading")

Do you want to learn new awesome concepts?

Then, start reading our “Userguide”!

It has everything you need! Reading order matters.

However, this is optional.

You can still use `returns` without a deep-dive into theory.

### Building your own stuff[¶](#building-your-own-stuff "Permalink to this heading")

You can extend `returns` and build your own stuff!

Particularly, you can add new interfaces, new containers, and new integrations.

See [this guide](index.html#create-your-own-container).

[![Telegram chat](https://img.shields.io/badge/chat-join-blue?logo=telegram)](https://t.me/drypython)

Join our chat to get help or advice.

Container: the concept[¶](#container-the-concept "Permalink to this heading")

-----------------------------------------------------------------------------

Container is a concept that allows you

to write code around the existing wrapped values

while maintaining the execution context.

List of supported containers:

* [`Maybe`](index.html#returns.maybe.Maybe "returns.maybe.Maybe") to handle `None` cases

* [`Result`](index.html#returns.result.Result "returns.result.Result") to handle possible exceptions

* [`IO`](index.html#returns.io.IO "returns.io.IO") to mark explicit `IO` actions

* [`Future`](index.html#returns.future.Future "returns.future.Future") to work with `async` code

* [`RequiresContext`](index.html#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")

to pass context to your functions (DI and similar)

There are also some combintations like

[`IOResult`](index.html#returns.io.IOResult "returns.io.IOResult"),

[`FutureResult`](index.html#returns.future.FutureResult "returns.future.FutureResult"),

[`RequiresContextResult`](index.html#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult"),

[`RequiresContextIOResult`](index.html#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult") and

[`RequiresContextFutureResult`](index.html#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult").

We will show you container’s simple API of one attribute

and several simple methods.

### Basics[¶](#basics "Permalink to this heading")

The main idea behind a container is that it wraps some internal state.

That’s what

`.\_inner\_value`

is used for.

And we have several functions

to create new containers based on the previous state.

And we can see how this state is evolving during the execution.

 graph LR

 F1["Container(Initial)"] --> F2["Container(UserId(1))"]

 F2 --> F3["Container(UserAccount(156))"]

 F3 --> F4["Container(FailedLoginAttempt(1))"]

 F4 --> F5["Container(SentNotificationId(992))"]

 

State evolution.[¶](#id3 "Permalink to this image")

### Working with a container[¶](#working-with-a-container "Permalink to this heading")

We use two methods to create a new container from the previous one.

`bind` and `map`.

The difference is simple:

* `map` works with functions that return regular value

* `bind` works with functions that return new container of the same type

We have [`returns.interfaces.mappable.MappableN.map()`](index.html#returns.interfaces.mappable.MappableN.map "returns.interfaces.mappable.MappableN.map")

to compose containers with regular functions.

Here’s how it looks:

 graph LR

 F1["Container[A]"] -- "map(function)" --> F2["Container[B]"]

 style F1 fill:green

 style F2 fill:green

 

Illustration of `map` method.[¶](#id4 "Permalink to this image")

```

>>> from typing import Any

>>> from returns.result import Success, Result

>>> def double(state: int) -> int:

...     return state \* 2

>>> result: Result[int, Any] = Success(1).map(double)

>>> assert str(result) == '<Success: 2>'

>>> result: Result[int, Any] = result.map(lambda state: state + 1)

>>> assert str(result) == '<Success: 3>'

```

The same works with built-in functions as well:

```

>>> from returns.io import IO

>>> io = IO('bytes').map(list)

>>> str(io)

"<IO: ['b', 'y', 't', 'e', 's']>"

```

The second method is `bind`. It is a bit different.

We pass a function that returns another container to it.

[`returns.interfaces.bindable.BindableN.bind()`](index.html#returns.interfaces.bindable.BindableN.bind "returns.interfaces.bindable.BindableN.bind")

is used to literally bind two different containers together.

Here’s how it looks:

 graph LR

 F1["Container[A]"] -- "bind(function)" --> F2["Container[B]"]

 F1["Container[A]"] -- "bind(function)" --> F3["Container[C]"]

 style F1 fill:green

 style F2 fill:green

 style F3 fill:red

 

Illustration of `bind` method.[¶](#id5 "Permalink to this image")

```

from returns.result import Result, Success

def may\_fail(user\_id: int) -> Result[float, str]:

    ...

value: Result[int, str] = Success(1)

# Can be assumed as either Success[float] or Failure[str]:

result: Result[float, str] = value.bind(may\_fail)

```

Note

All containers support these methods.

Because all containers implement

[`returns.interfaces.mappable.MappableN`](index.html#returns.interfaces.mappable.MappableN "returns.interfaces.mappable.MappableN")

and

[`returns.interfaces.bindable.BindableN`](index.html#returns.interfaces.bindable.BindableN "returns.interfaces.bindable.BindableN").

You can read more about methods

that some other containers support

and [interfaces](#base-interfaces) behind them.

### Instantiating a container[¶](#instantiating-a-container "Permalink to this heading")

All [`returns.interfaces.applicative.ApplicativeN`](index.html#returns.interfaces.applicative.ApplicativeN "returns.interfaces.applicative.ApplicativeN") containers

support special `.from\_value` method

to construct a new container from a raw value.

```

>>> from returns.result import Result

>>> assert str(Result.from\_value(1)) == '<Success: 1>'

```

There are also other methods in other interfaces.

For example, here are some of them:

* [`returns.interfaces.specific.maybe.MaybeLikeN.from\_optional()`](index.html#returns.interfaces.specific.maybe.MaybeLikeN.from_optional "returns.interfaces.specific.maybe.MaybeLikeN.from_optional")

creates a value from `Optional` value

```

>>> from returns.maybe import Maybe, Some, Nothing

>>> assert Maybe.from\_optional(1) == Some(1)

>>> assert Maybe.from\_optional(None) == Nothing

```

* [`returns.interfaces.failable.DiverseFailableN.from\_failure()`](index.html#returns.interfaces.failable.DiverseFailableN.from_failure "returns.interfaces.failable.DiverseFailableN.from_failure")

creates a failing container from a value

```

>>> from returns.result import Result, Failure

>>> assert Result.from\_failure(1) == Failure(1)

```

There are many other constructors!

Check out concrete types and their interfaces.

### Working with multiple containers[¶](#working-with-multiple-containers "Permalink to this heading")

#### Multiple container arguments[¶](#multiple-container-arguments "Permalink to this heading")

We have already seen how we can work with one container and functions

that receive a single argument.

Let’s say you have a function of two arguments and two containers:

```

>>> def sum\_two\_numbers(first: int, second: int) -> int:

...     return first + second

```

And here are our two containers:

```

>>> from returns.io import IO

>>> one = IO(1)

>>> two = IO(2)

```

The naive approach to compose two `IO` containers and a function

would be too hard to show here.

Luckily, we support partial application and the `.apply()` method.

Here are the required steps:

0. We make `sum\_two\_numbers` to receive [partial arguments](index.html#curry)

1. We create a new container that wraps `sum\_two\_numbers` function as a value

2. We then call `.apply()` twice to pass each value

It can be done like so:

```

>>> from returns.curry import curry

>>> from returns.io import IO

>>> @curry

... def sum\_two\_numbers(first: int, second: int) -> int:

...     return first + second

>>> one = IO(1)

>>> two = IO(2)

>>> assert two.apply(one.apply(IO(sum\_two\_numbers))) == IO(3)

```

But, there are other ways to make `sum\_two\_numbers` partial.

One can use `partial` as well:

```

>>> from returns.curry import partial

>>> one = IO(1)

>>> two = IO(2)

>>> assert two.apply(one.apply(

...     IO(lambda x: partial(sum\_two\_numbers, x)),

... )) == IO(3)

```

Or even native `lambda` functions:

```

>>> one = IO(1)

>>> two = IO(2)

>>> assert two.apply(one.apply(

...     IO(lambda x: lambda y: sum\_two\_numbers(x, y)),

... )) == IO(3)

```

It would be faster, but not as elegant (and type-safe).

#### Working with iterable of containers[¶](#working-with-iterable-of-containers "Permalink to this heading")

Imagine that you have two take 10 random numbers

and then sum they to get the final result.

So, here’s how your code will look like:

```

>>> import random

>>> from returns.io import IO

>>> def random\_number() -> IO[int]:

...     return IO(2)  # Example, basically alias of ``random.randint(1, 5)``

>>> numbers = [random\_number() for \_ in range(10)]

>>> assert len(numbers) == 10

>>> assert all(isinstance(number, IO) for number in numbers)

```

So, how to sum these random values into a single `IO[int]` value?

That’s where

[`Fold.loop`](index.html#returns.iterables.AbstractFold.loop "returns.iterables.AbstractFold.loop") really helps!

```

>>> from typing import Callable

>>> from returns.iterables import Fold

>>> def sum\_two\_numbers(first: int) -> Callable[[int], int]:

...     return lambda second: first + second

>>> assert Fold.loop(

...     numbers,  # let's loop on our ``IO`` values

...     IO(0),  # starting from ``0`` value

...     sum\_two\_numbers,  # and getting the sum of each two numbers in a loop

... ) == IO(20)

```

We can also change the initial element to some other value:

```

>>> assert Fold.loop(

...     numbers,

...     IO(5),  # now we will start from ``5``, not ``0`

...     sum\_two\_numbers,

... ) == IO(25)

```

`Fold.loop` is eager. It will be executed for all items in your iterable.

#### Collecting an iterable of containers into a single container[¶](#collecting-an-iterable-of-containers-into-a-single-container "Permalink to this heading")

You might end up with an iterable of containers:

```

>>> from typing import List

>>> from returns.maybe import Maybe, Some, Nothing, maybe

>>> source = {'a': 1, 'b': 2}

>>> fetched\_values: List[Maybe[int]] = [

...     maybe(source.get)(key)

...     for key in ('a', 'b')

... ]

```

To work with iterable of containers,

it is recommended to cast it into a container with the iterable inside

using the [`Fold.collect`](index.html#returns.iterables.AbstractFold.collect "returns.iterables.AbstractFold.collect") method:

```

>>> from returns.iterables import Fold

>>> assert Fold.collect(fetched\_values, Some(())) == Some((1, 2))

```

Any falsy values will result in a falsy result (pun intended):

```

>>> fetched\_values: List[Maybe[int]] = [

...     maybe(source.get)(key)

...     for key in ('a', 'c')  # 'c' is missing!

... ]

>>> assert Fold.collect(fetched\_values, Some(())) == Nothing

```

You can also use a different strategy to fetch values you need,

to do just that we have

[`Fold.collect\_all`](index.html#returns.iterables.AbstractFold.collect_all "returns.iterables.AbstractFold.collect_all") method:

```

>>> fetched\_values: Maybe[int] = [

...     maybe(source.get)(key)

...     for key in ('a', 'c')  # 'c' is missing!

... ]

>>> assert Fold.collect\_all(fetched\_values, Some(())) == Some((1,))

```

We support any `Iterable[T]` input type

and return a `Container[Sequence[T]]`.

You can subclass `Fold` type to change how any of these methods work.

### Immutability[¶](#immutability "Permalink to this heading")

We like to think of `returns`

as [immutable](index.html#primitive-types) structures.

You cannot mutate the inner state of the created container,

because we redefine `\_\_setattr\_\_` and `\_\_delattr\_\_` magic methods.

You cannot also set new attributes to container instances,

since we are using `\_\_slots\_\_` for better performance and strictness.

Well, nothing is **really** immutable in python, but you were warned.

We also provide [`returns.primitives.types.Immutable`](index.html#returns.primitives.types.Immutable "returns.primitives.types.Immutable") mixin

that users can use to quickly make their classes immutable.

### Type safety[¶](#type-safety "Permalink to this heading")

We try to make our containers optionally type safe.

What does it mean?

1. It is still good old `python`, do whatever you want without `mypy`

2. If you are using `mypy` you will be notified about type violations

We also ship [PEP561](https://www.python.org/dev/peps/pep-0561/)

compatible `.pyi` files together with the source code.

In this case these types will be available to users

when they install our application.

We also ship custom `mypy` plugins to overcome some existing problems,

please make sure to use them,

since they increase your developer experience and type-safety level:

Check out our docs on using our [mypy plugins](index.html#mypy-plugins).

### Further reading[¶](#further-reading "Permalink to this heading")

* [Railway oriented programming](index.html#railway)

### API Reference[¶](#api-reference "Permalink to this heading")

`BaseContainer` is a base class for all other containers.

It defines some basic things like representation, hashing, pickling, etc.

 classDiagram

 Immutable <|-- BaseContainer

 dict <|-- \_PickleState

 

*class* BaseContainer(*inner\_value*)[[source]](_modules/returns/primitives/container.html#BaseContainer)[¶](#returns.primitives.container.BaseContainer "Permalink to this definition")

Bases: [`Immutable`](index.html#returns.primitives.types.Immutable "returns.primitives.types.Immutable")

Utility class to provide all needed magic methods to the context.

\_\_slots\_\_ *= ('\_inner\_value',)*[¶](#returns.primitives.container.BaseContainer.__slots__ "Permalink to this definition")

\_\_init\_\_(*inner\_value*)[[source]](_modules/returns/primitives/container.html#BaseContainer.__init__)[¶](#returns.primitives.container.BaseContainer.__init__ "Permalink to this definition")

Wraps the given value in the Container.

‘value’ is any arbitrary value of any type including functions.

\_\_repr\_\_()[[source]](_modules/returns/primitives/container.html#BaseContainer.__repr__)[¶](#returns.primitives.container.BaseContainer.__repr__ "Permalink to this definition")

Used to display details of object.

Return type:

`str`

\_\_eq\_\_(*other*)[[source]](_modules/returns/primitives/container.html#BaseContainer.__eq__)[¶](#returns.primitives.container.BaseContainer.__eq__ "Permalink to this definition")

Used to compare two ‘Container’ objects.

Parameters:

**other** (`Any`) – 

Return type:

`bool`

\_\_hash\_\_()[[source]](_modules/returns/primitives/container.html#BaseContainer.__hash__)[¶](#returns.primitives.container.BaseContainer.__hash__ "Permalink to this definition")

Used to use this value as a key.

Return type:

`int`

\_\_getstate\_\_()[[source]](_modules/returns/primitives/container.html#BaseContainer.__getstate__)[¶](#returns.primitives.container.BaseContainer.__getstate__ "Permalink to this definition")

That’s how this object will be pickled.

Return type:

`\_PickleState`

\_\_setstate\_\_(*state*)[[source]](_modules/returns/primitives/container.html#BaseContainer.__setstate__)[¶](#returns.primitives.container.BaseContainer.__setstate__ "Permalink to this definition")

Loading state from pickled data.

Parameters:

**state** (`Union`[`\_PickleState`, `Any`]) – 

Return type:

`None`

\_\_abstractmethods\_\_ *= frozenset({})*[¶](#returns.primitives.container.BaseContainer.__abstractmethods__ "Permalink to this definition")

\_\_annotations\_\_ *= {'\_inner\_value': typing.Any}*[¶](#returns.primitives.container.BaseContainer.__annotations__ "Permalink to this definition")

\_\_module\_\_ *= 'returns.primitives.container'*[¶](#returns.primitives.container.BaseContainer.__module__ "Permalink to this definition")

container\_equality(*self*, *other*)[[source]](_modules/returns/primitives/container.html#container_equality)[¶](#returns.primitives.container.container_equality "Permalink to this definition")

Function to compare similar containers.

Compares both their types and their inner values.

Parameters:

* **self** ([`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_EqualType`, bound= [`Equable`](index.html#returns.interfaces.equable.Equable "returns.interfaces.equable.Equable")), `Any`, `Any`, `Any`]) –

* **other** ([`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_EqualType`, bound= [`Equable`](index.html#returns.interfaces.equable.Equable "returns.interfaces.equable.Equable")), `Any`, `Any`, `Any`]) –

Return type:

`bool`

Railway oriented programming[¶](#railway-oriented-programming "Permalink to this heading")

------------------------------------------------------------------------------------------

Containers can serve many different purposes

(while still serving the main one: composition)

for example, some of them

([`Result`](index.html#returns.result.Result "returns.result.Result") and [`Maybe`](index.html#returns.maybe.Maybe "returns.maybe.Maybe")) are used

to work with different types of errors

starting with `NullPointerException` to arbitrary user-defined ones.

### Error handling[¶](#error-handling "Permalink to this heading")

When talking about error handling we use a concept of

[Railway oriented programming](https://fsharpforfunandprofit.com/rop/).

It means that flow of our program has two tracks:

1. Successful one: where everything goes perfectly: HTTP requests work,

database is always serving us data, parsing values does not fail

2. Failed one: where something went wrong

We can switch from track to track: we can fail something

or we can fix the situation.

 graph LR

 S1 -- bind --> S3

 S1 -- bind --> F2

 S3 -- map --> S5

 S5 -- bind --> S7

 S5 -- bind --> F6

 F2 -- alt --> F4

 F4 -- lash --> F6

 F4 -- lash --> S5

 F6 -- lash --> F8

 F6 -- lash --> S7

 style S1 fill:green

 style S3 fill:green

 style S5 fill:green

 style S7 fill:green

 style F2 fill:red

 style F4 fill:red

 style F6 fill:red

 style F8 fill:red

 

Railway oriented programming.[¶](#id2 "Permalink to this image")

#### Returning execution to the right track[¶](#returning-execution-to-the-right-track "Permalink to this heading")

We also support two special methods to work with “failed” values:

* [`returns.interfaces.altable.AltableN.alt()`](index.html#returns.interfaces.altable.AltableN.alt "returns.interfaces.altable.AltableN.alt")

transforms error to another error

that works only when container is in failed state,

is the opposite of [`returns.interfaces.mappable.MappableN.map()`](index.html#returns.interfaces.mappable.MappableN.map "returns.interfaces.mappable.MappableN.map") method

* [`returns.interfaces.lashable.LashableN.lash()`](index.html#returns.interfaces.lashable.LashableN.lash "returns.interfaces.lashable.LashableN.lash")

is the opposite of [`returns.interfaces.bindable.BindableN.bind()`](index.html#returns.interfaces.bindable.BindableN.bind "returns.interfaces.bindable.BindableN.bind") method

that works only when container is in failed state

Let’s start from the first one:

`alt` method allows to change your error type.

 graph LR

 F1["Container[A]"] -- "alt(function)" --> F2["Container[B]"]

 style F1 fill:red

 style F2 fill:red

 

Illustration of `alt` method.[¶](#id3 "Permalink to this image")

```

>>> from returns.result import Failure

>>> assert Failure(1).alt(str) == Failure('1')

```

The second method is `lash`. It is a bit different.

We pass a function that returns another container to it.

[`returns.interfaces.lashable.LashableN.lash()`](index.html#returns.interfaces.lashable.LashableN.lash "returns.interfaces.lashable.LashableN.lash")

is used to literally bind two different containers together.

It can also lash your flow and get on the successful track again:

 graph LR

 F1["Container[A]"] -- "lash(function)" --> F2["Container[B]"]

 F1["Container[A]"] -- "lash(function)" --> F3["Container[C]"]

 style F1 fill:red

 style F2 fill:green

 style F3 fill:red

 

Illustration of `lash` method.[¶](#id4 "Permalink to this image")

```

>>> from returns.result import Result, Failure, Success

>>> def tolerate\_exception(state: Exception) -> Result[int, Exception]:

...     if isinstance(state, ZeroDivisionError):

...         return Success(0)

...     return Failure(state)

>>> value: Result[int, Exception] = Failure(ZeroDivisionError())

>>> result: Result[int, Exception] = value.lash(tolerate\_exception)

>>> assert result == Success(0)

>>> value2: Result[int, Exception] = Failure(ValueError())

>>> result2: Result[int, Exception] = value2.lash(tolerate\_exception)

>>> # => Failure(ValueError())

```

From typing perspective `.alt` and `.lash`

are exactly the same as `.map` and `.bind`

but only work with the second type argument instead of the first one:

```

from returns.result import Result

first: Result[int, int]

second: Result[int, int]

reveal\_type(first.map(str))

# => Result[str, int]

reveal\_type(second.alt(str))

# => Result[int, str]

```

Note

Not all containers support these methods,

only containers that implement

[`returns.interfaces.lashable.LashableN`](index.html#returns.interfaces.lashable.LashableN "returns.interfaces.lashable.LashableN")

and

[`returns.interfaces.altable.AltableN`](index.html#returns.interfaces.altable.AltableN "returns.interfaces.altable.AltableN")

For example, [`IO`](index.html#returns.io.IO "returns.io.IO") based containers

and [`RequiresContext`](index.html#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")

cannot be alted or lashed.

### Unwrapping values[¶](#unwrapping-values "Permalink to this heading")

And we have two more functions to unwrap

inner state of containers into a regular types:

* `.unwrap`

returns a value if it is possible,

raises [`returns.primitives.exceptions.UnwrapFailedError`](index.html#returns.primitives.exceptions.UnwrapFailedError "returns.primitives.exceptions.UnwrapFailedError") otherwise

```

>>> from returns.result import Failure, Success

>>> from returns.maybe import Some, Nothing

>>> assert Success(1).value\_or(None) == 1

>>> assert Some(0).unwrap() == 0

```

```

>>> Failure(1).unwrap()

Traceback (most recent call last):

 ...

returns.primitives.exceptions.UnwrapFailedError

>>> Nothing.unwrap()

Traceback (most recent call last):

 ...

returns.primitives.exceptions.UnwrapFailedError

```

For failing containers you can

use `returns.interfaces.unwrappable.Unwrapable.failure()`

to unwrap the failed state:

```

>>> assert Failure(1).failure() == 1

>>> Success(1).failure()

Traceback (most recent call last):

 ...

returns.primitives.exceptions.UnwrapFailedError

```

Be careful, since this method will raise an exception

when you try to `.failure()` a successful container.

Note

Not all containers support these methods,

only containers that implement

[`returns.interfaces.unwrappable.Unwrappable`](index.html#returns.interfaces.unwrappable.Unwrappable "returns.interfaces.unwrappable.Unwrappable").

For example, [`IO`](index.html#returns.io.IO "returns.io.IO") based containers

and [`RequiresContext`](index.html#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")

cannot be unwrapped.

Note

Some containers also have `.value\_or()` helper method.

Example:

```

>>> from returns.result import Success, Failure

>>> assert Success(1).value\_or(None) == 1

>>> assert Failure(1).value\_or(None) is None

```

### Further reading[¶](#further-reading "Permalink to this heading")

* [Railway oriented programming in F#](https://fsharpforfunandprofit.com/rop/)

* [Against Railway-Oriented Programming](https://fsharpforfunandprofit.com/posts/against-railway-oriented-programming/)

Higher Kinded Types[¶](#higher-kinded-types "Permalink to this heading")

------------------------------------------------------------------------

Higher Kinded Types is a new concept for Python developers.

But, it is totally not new in general!

So, let’s start with the detailed explanation: what Higher Kinded Types are?

### Regular types[¶](#regular-types "Permalink to this heading")

We can start with the very basic example.

Let’s say we have a function that transforms type `A` into a type `B`.

These types `A` and `B` can be some specific ones, for example:

```

>>> def from\_a\_to\_b(arg: int) -> str:

...      return str(arg)

>>> assert from\_a\_to\_b(1) == '1'

```

That’s what we already know and use. Let’s scale things up!

### Generics[¶](#generics "Permalink to this heading")

The next thing we can do with types is to write generic types.

What are generic types?

Basically, they are some types that contain other types inside.

Like `List[int]` is a list of integers: `[1, 2, 3]`.

We know that `List[int]` has a shape of a `list` and contents of `int`.

We can also write functions that work with generics:

```

>>> from typing import List

>>> def all\_to\_str(arg: List[int]) -> List[str]:

...     return [str(item) for item in arg]

>>> assert all\_to\_str([1, 2]) == ['1', '2']

```

There’s one more thing about generics we want to notice at this point.

Different generics do have different numbers of type arguments:

* `List` has a single type argument:

`List[Value]` or `Maybe[Value]`

* `Dict` has two type arguments:

`Dict[Key, Value]` or `Result[Value, Error]`

* `Generator` has three type arguments: `Generator[Yield, Send, Return]`

or `RequiresContextResult[Value, Error, Env]`

That’s what we call a kind.

So, `List` and `Maybe` have a kind of `1`,

`Dict` and `Result` have kind of `2`,

`Generator` and `RequiresContextResult` have a kind of `3`.

So, let’s go one level further.

### Operations on generics[¶](#operations-on-generics "Permalink to this heading")

Let’s say you have a function that copies all values of a passed argument.

We can define this function as:

```

>>> from typing import TypeVar

>>> ValueType = TypeVar('ValueType')

>>> def copy(arg: ValueType) -> ValueType:

...    ...

```

This function can work with any type.

It receives something and then returns the same value back.

That’s the whole point of copying!

But, there are different functions, that do different things with types.

For example, we can write a function that converts

a value inside any [`Container1`](index.html#returns.interfaces.container.ContainerN "returns.interfaces.container.ContainerN")

(a base class for all our containers)

from `int` to `str`:

We can also write functions that work with generics:

```

>>> from returns.interfaces.container import Container1

>>> def to\_str(container: Container1[int]) -> Container1[str]:

...     return container.map(str)

```

And here’s how it can be used:

```

>>> from returns.maybe import Maybe

>>> from returns.io import IO

>>> assert to\_str(Maybe.from\_value(1)) == Maybe.from\_value('1')

>>> assert to\_str(IO.from\_value(1)) == IO.from\_value('1')

```

It works just fine! But! It has a very important thing inside.

All calls to `to\_str` will return `Container1` type,

not something specific:

```

reveal\_type(to\_str(Maybe.from\_value(1)))  # Container1[str]

reveal\_type(to\_str(IO.from\_value(1)))     # Container1[str]

```

But, we know that this is not true.

When we pass a `Maybe` in - we get the `Maybe` back.

When we pass a `IO` in - we get the `IO` back.

How can we fix this problem? With `@overload`!

```

>>> from typing import overload

>>> from returns.maybe import Maybe

>>> from returns.io import IO

>>> @overload

... def to\_str(arg: Maybe[int]) -> Maybe[str]:

...    ...

>>> @overload

... def to\_str(arg: IO[int]) -> IO[str]:

...    ...

```

We kinda fixed it!

Now, our calls will reveal the correct types for these three examples:

```

reveal\_type(to\_str(Maybe.from\_value(1)))  # Maybe[str]

reveal\_type(to\_str(IO.from\_value(1)))     # IO[str]

```

But, there’s an important limitation with this solution:

no other types are allowed in this function anymore.

So, you will try to use it with any other type, it won’t be possible.

### Current limitations[¶](#current-limitations "Permalink to this heading")

To overcome current `@overload` decorators limitations,

we can imagine a syntax like this:

```

from typing import TypeVar

from returns.interfaces.container import Container1

T = TypeVar('T', bound=Container1)

def all\_to\_str(arg: T[int]) -> T[str]:

    ...

```

Sadly, this does not work. Because `TypeVar` cannot be used with `[]`.

We have to find some other way.

### Higher Kinded Types[¶](#id1 "Permalink to this heading")

So, that’s where `returns` saves the day!

Note

Technical note: this feature requires [mypy plugin](index.html#mypy-plugins).

The main idea is that we can rewrite `T[int]` as `Kind1[T, int]`.

Let’s see how it works:

```

>>> from returns.primitives.hkt import Kind1

>>> from returns.interfaces.container import ContainerN

>>> from typing import TypeVar

>>> T = TypeVar('T', bound=ContainerN)

>>> def to\_str(container: Kind1[T, int]) -> Kind1[T, str]:

...     return container.map(str)

```

Now, this will work almost correctly!

Why almost? Because the revealed type will be `Kind1`.

```

reveal\_type(to\_str(Maybe.from\_value(1)))  # Kind1[Maybe, str]

reveal\_type(to\_str(IO.from\_value(1)))     # Kind1[IO, str]

```

That’s not something we want. We don’t need `Kind1`,

we need real `Maybe` or `IO` values.

The final solution is to decorate `to\_str` with `@kinded`:

```

>>> from returns.primitives.hkt import kinded

>>> @kinded

... def to\_str(container: Kind1[T, int]) -> Kind1[T, str]:

...     return container.map(str)

```

Now, it will be fully working:

```

reveal\_type(to\_str(Maybe.from\_value(1)))  # Maybe[str]

reveal\_type(to\_str(IO.from\_value(1)))     # IO[str]

```

And the thing about this approach is that it will be:

1. Fully type-safe. It works with correct interface `ContainerN`,

returns the correct type, has correct type transformation

2. Is opened for further extension and even custom types

### Kinds[¶](#kinds "Permalink to this heading")

As it was said `Maybe[int]`, `Result[str, int]`,

and `RequiresContextResult[str, int, bool]` are different

in terms of a number of type arguments.

We support different kinds:

* `Kind1[Maybe, int]` is similar to `Maybe[int]`

* `Kind2[Result, str, int]` is similar to `Result[str, int]`

* `Kind3[RequiresContextResult, str, int, bool]`

is similar to `RequiresContextResult[str, int, bool]`

You can use any of them freely.

Later you will learn how to

[create your own types](index.html#create-your-own-container) that support kinds!

### Further reading[¶](#further-reading "Permalink to this heading")

* [Higher Kinded Types in Python](https://sobolevn.me/2020/10/higher-kinded-types-in-python)

### FAQ[¶](#faq "Permalink to this heading")

#### Which types you can use with KindN?[¶](#which-types-you-can-use-with-kindn "Permalink to this heading")

The first position in all `KindN` types

can be occupied by either `Instance` type or `TypeVar` with `bound=`.

Let’s see an example:

```

>>> from typing import TypeVar

>>> from returns.primitives.hkt import KindN, kinded

>>> from returns.interfaces.mappable import MappableN

>>> \_FirstType = TypeVar('\_FirstType')

>>> \_SecondType = TypeVar('\_SecondType')

>>> \_ThirdType = TypeVar('\_ThirdType')

>>> \_MappableKind = TypeVar('\_MappableKind', bound=MappableN)

>>> @kinded

... def works\_with\_interface(

...     container: KindN[\_MappableKind, \_FirstType, \_SecondType, \_ThirdType],

... ) -> KindN[\_MappableKind, str, \_SecondType, \_ThirdType]:

...     return container.map(str)

```

This version of `works\_with\_interface` will work

with any subtype of `MappableN`.

Because we use `\_MappableKind` in its definition.

And `\_MappableKind` is a `TypeVar` bound to `MappableN`.

Arguments of non `MappableN` subtypes will be rejected by a type-checker:

```

>>> from returns.maybe import Maybe

>>> from returns.io import IO

>>> from returns.result import Success

>>> assert works\_with\_interface(Maybe.from\_value(1)) == Maybe.from\_value('1')

>>> assert works\_with\_interface(IO.from\_value(1)) == IO.from\_value('1')

>>> assert works\_with\_interface(Success(1)) == Success('1')

```

In contrast, we can work directly with some specific type,

let’s say `Maybe` container:

```

>>> from returns.maybe import Maybe

>>> @kinded

... def works\_with\_maybe(

...     container: KindN[Maybe, \_FirstType, \_SecondType, \_ThirdType],

... ) -> KindN[Maybe, str, \_SecondType, \_ThirdType]:

...     return container.map(str)

>>> assert works\_with\_maybe(Maybe.from\_value(1)) == Maybe.from\_value('1')

```

Function `works\_with\_maybe` will work correctly with `Maybe` instance.

Other types will be rejected.

So, choose wisely which mechanism you need.

### API Reference[¶](#api-reference "Permalink to this heading")

 classDiagram

 Generic <|-- KindN

 KindN <|-- SupportsKindN

 Protocol <|-- Kinded

 

*class* KindN[[source]](_modules/returns/primitives/hkt.html#KindN)[¶](#returns.primitives.hkt.KindN "Permalink to this definition")

Bases: `Generic`[`\_InstanceType`, `\_TypeArgType1`, `\_TypeArgType2`, `\_TypeArgType3`]

Emulation support for Higher Kinded Types.

Consider `KindN` to be an alias of `Generic` type.

But with some extra goodies.

`KindN` is the top-most type for other `Kind` types

like `Kind1`, `Kind2`, `Kind3`, etc.

The only difference between them is how many type arguments they can hold.

`Kind1` can hold just two type arguments: `Kind1[IO, int]`

which is almost equals to `IO[int]`.

`Kind2` can hold just two type arguments: `Kind2[IOResult, int, str]`

which is almost equals to `IOResult[int, str]`.

And so on.

The idea behind `KindN` is that one cannot write this code:

```

from typing import TypeVar

T = TypeVar('T')

V = TypeVar('V')

def impossible(generic: T, value: V) -> T[V]:

    return generic(value)

```

But, with `KindN` this becomes possible in a form of `Kind1[T, V]`.

Note

To make sure it works correctly,

your type has to be a subtype of `KindN`.

We use a custom `mypy` plugin to make sure types are correct.

Otherwise, it is currently impossible to properly type this.

We use “emulated Higher Kinded Types” concept.

Read the whitepaper: <https://bit.ly/2ABACx2>

`KindN` does not exist in runtime. It is used just for typing.

There are (and must be) no instances of this type directly.

Implementation details

We didn’t use `ABCMeta` to disallow its creation,

because we don’t want to have

a possible metaclass conflict with other metaclasses.

Current API allows you to mix `KindN` anywhere.

We allow `\_InstanceType` of `KindN`

to be `Instance` type or `TypeVarType` with `bound=...`.

See also

* <https://arrow-kt.io/docs/0.10/patterns/glossary/#higher-kinds>

* <https://github.com/gcanti/fp-ts/blob/master/docs/guides/HKT.md>

* <https://bow-swift.io/docs/fp-concepts/higher-kinded-types>

* <https://github.com/pelotom/hkts>

Kind1[¶](#returns.primitives.hkt.Kind1 "Permalink to this definition")

Type alias for kinds with one type argument.

alias of [`KindN`](#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`\_InstanceType`, `\_TypeArgType1`, `Any`, `Any`]

Kind2[¶](#returns.primitives.hkt.Kind2 "Permalink to this definition")

Type alias for kinds with two type arguments.

alias of [`KindN`](#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`\_InstanceType`, `\_TypeArgType1`, `\_TypeArgType2`, `Any`]

Kind3[¶](#returns.primitives.hkt.Kind3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`KindN`](#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`\_InstanceType`, `\_TypeArgType1`, `\_TypeArgType2`, `\_TypeArgType3`]

*class* SupportsKindN[[source]](_modules/returns/primitives/hkt.html#SupportsKindN)[¶](#returns.primitives.hkt.SupportsKindN "Permalink to this definition")

Bases: [`KindN`](#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`\_InstanceType`, `\_TypeArgType1`, `\_TypeArgType2`, `\_TypeArgType3`]

Base class for your containers.

Notice, that we use `KindN` / `Kind1` to annotate values,

but we use `SupportsKindN` / `SupportsKind1` to inherit from.

Implementation details

The only thing this class does is: making sure that the resulting classes

won’t have `\_\_getattr\_\_` available during the typechecking phase.

Needless to say, that `\_\_getattr\_\_` during runtime - never exists at all.

SupportsKind1[¶](#returns.primitives.hkt.SupportsKind1 "Permalink to this definition")

Type alias used for inheritance with one type argument.

alias of [`SupportsKindN`](#returns.primitives.hkt.SupportsKindN "returns.primitives.hkt.SupportsKindN")[`\_InstanceType`, `\_TypeArgType1`, `NoReturn`, `NoReturn`]

SupportsKind2[¶](#returns.primitives.hkt.SupportsKind2 "Permalink to this definition")

Type alias used for inheritance with two type arguments.

alias of [`SupportsKindN`](#returns.primitives.hkt.SupportsKindN "returns.primitives.hkt.SupportsKindN")[`\_InstanceType`, `\_TypeArgType1`, `\_TypeArgType2`, `NoReturn`]

SupportsKind3[¶](#returns.primitives.hkt.SupportsKind3 "Permalink to this definition")

Type alias used for inheritance with three type arguments.

alias of [`SupportsKindN`](#returns.primitives.hkt.SupportsKindN "returns.primitives.hkt.SupportsKindN")[`\_InstanceType`, `\_TypeArgType1`, `\_TypeArgType2`, `\_TypeArgType3`]

dekind(*kind*)[[source]](_modules/returns/primitives/hkt.html#dekind)[¶](#returns.primitives.hkt.dekind "Permalink to this definition")

Turns `Kind1[IO, int]` type into real `IO[int]` type.

Should be used when you are left with accidental `KindN` instance

when you really want to have the real type.

Works with type arguments of any length.

We use a custom `mypy` plugin to make sure types are correct.

Otherwise, it is currently impossible to properly type this.

In runtime it just returns the passed argument, nothing really happens:

```

>>> from returns.io import IO

>>> from returns.primitives.hkt import Kind1

>>> container: Kind1[IO, int] = IO(1)

>>> assert dekind(container) is container

```

However, please, do not use this function

unless you know exactly what you are doing and why do you need it.

Parameters:

**kind** ([`KindN`](#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_InstanceType`, covariant=True), `TypeVar`(`\_TypeArgType1`, covariant=True), `TypeVar`(`\_TypeArgType2`, covariant=True), `TypeVar`(`\_TypeArgType3`, covariant=True)]) – 

Return type:

`TypeVar`(`\_InstanceType`, covariant=True)

*class* Kinded(*\*args*, *\*\*kwargs*)[[source]](_modules/returns/primitives/hkt.html#Kinded)[¶](#returns.primitives.hkt.Kinded "Permalink to this definition")

Bases: `Protocol`[`\_FunctionDefType`]

Protocol that tracks kinded functions calls.

We use a custom `mypy` plugin to make sure types are correct.

Otherwise, it is currently impossible to properly type this.

kinded(*function*)[[source]](_modules/returns/primitives/hkt.html#kinded)[¶](#returns.primitives.hkt.kinded "Permalink to this definition")

Decorator to be used when you want to dekind the function’s return type.

Does nothing in runtime, just returns its argument.

We use a custom `mypy` plugin to make sure types are correct.

Otherwise, it is currently impossible to properly type this.

Here’s an example of how it should be used:

```

>>> from typing import TypeVar

>>> from returns.primitives.hkt import KindN, kinded

>>> from returns.interfaces.bindable import BindableN

>>> \_Binds = TypeVar('\_Binds', bound=BindableN)  # just an example

>>> \_Type1 = TypeVar('\_Type1')

>>> \_Type2 = TypeVar('\_Type2')

>>> \_Type3 = TypeVar('\_Type3')

>>> @kinded

... def bindable\_identity(

...    container: KindN[\_Binds, \_Type1, \_Type2, \_Type3],

... ) -> KindN[\_Binds, \_Type1, \_Type2, \_Type3]:

...     return container  # just do nothing

```

As you can see, here we annotate our return type as

`-> KindN[\_Binds, \_Type1, \_Type2, \_Type3]`,

it would be true without `@kinded` decorator.

But, `@kinded` decorator dekinds the return type and infers

the real type behind it:

```

>>> from returns.io import IO, IOResult

>>> assert bindable\_identity(IO(1)) == IO(1)

>>> # => Revealed type: 'IO[int]'

>>> iores: IOResult[int, str] = IOResult.from\_value(1)

>>> assert bindable\_identity(iores) == iores

>>> # => Revealed type: 'IOResult[int, str]'

```

The difference is very clear in `methods` modules, like:

* Raw `returns.methods.bind.internal\_bind()`

that returns `KindN` instance

* User-facing `returns.methods.bind.bind()`

that returns the container type

You must use this decorator for your own kinded functions as well.

Parameters:

**function** (`TypeVar`(`\_FunctionType`, bound= `Callable`)) – 

Return type:

[`Kinded`](#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded")[`TypeVar`(`\_FunctionType`, bound= `Callable`)]

Interfaces[¶](#interfaces "Permalink to this heading")

------------------------------------------------------

We provide a lot of generic interfaces

to write our bundled and your own custom types.

These interfaces are designed:

1. To be subclassed

2. To provide abstract methods to implement in your own types

3. To enforce correctness on final types

4. To attach critical laws to be checked

We use [Higher Kinded Types](index.html#hkt) to define abstract methods.

Reading about interfaces will be the most useful

if you plan to [create your own containers](index.html#create-your-own-container).

### General information[¶](#general-information "Permalink to this heading")

All the non-specific interfaces (e.g. MappableN, BindableN, ApplicativeN) can

have **Nth** types, at the maximum of three possible types.

What does this mean?

[`MappableN`](#returns.interfaces.mappable.MappableN "returns.interfaces.mappable.MappableN") interface,

for example, can have one, two or three possible types. See the example below:

```

>>> from typing import NoReturn

>>> from returns.interfaces.mappable import (

...    MappableN, Mappable1, Mappable2, Mappable3,

... )

>>> one\_type: MappableN[int, NoReturn, NoReturn]

>>> two\_types: MappableN[int, str, NoReturn]

>>> three\_types: MappableN[int, str, bool]

>>> # We have a shortcut for each amount of arguments to reduce the boilerplate

>>> one\_type: Mappable1[int]

>>> two\_types: Mappable2[int, str]

>>> three\_type: Mappable3[int, str, bool]

```

Note

Useful links before you start here:

* [Functors, Applicatives, And Monads In Pictures](http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html)

* [Understanding Functor and Monad With a Bag of Peanuts](https://medium.com/beingprofessional/understanding-functor-and-monad-with-a-bag-of-peanuts-8fa702b3f69e)

* [Variance of generic types](https://mypy.readthedocs.io/en/latest/generics.html#variance-of-generic-types)

* [If you know map, I will teach you monads](https://www.youtube.com/watch?v=cB0vpg9-YMQ)

#### Naming convention[¶](#naming-convention "Permalink to this heading")

We follow a very specific naming convention in our interface names.

If interface does not depend on the number of types

it works with and is always the same, we name it as is.

For example, `Equable` is always the same

and does not depend on the number of type arguments.

We use adjectives to name these interfaces.

Secondly, if interface depends on the number of type arguments,

it is named with `N` suffix in the end.

It would always have numeric aliases for each number of arguments supported.

For example, `MappableN`, `Mappable1`, `Mappable2`, and `Mappable3`.

The last criteria we have to decided on naming is

“whether this interface always the same or it can have slight variations”?

That’s why we have `ResultLikeN` and `ResultBasedN` interfaces.

Because `ResultBasedN` has two extra methods compared to `ResultLikeN`.

We use `Like` suffix for interfaces that describes some similar types.

We use `Based` suffix for interfaces that descire almost concrete types.

#### Laws[¶](#laws "Permalink to this heading")

Some interfaces define its laws as values.

These laws can be viewed as tests that are attached to the specific interface.

We are able to check them of any type

that implements a given interfaces with laws

by our own [check\_all\_laws hypothesis plugin](index.html#hypothesis-plugins).

In this docs we are going to describe each general interface and its laws.

### Mappable[¶](#mappable "Permalink to this heading")

Something is considered mappable if we can `map` it using a function,

generally `map` is a method that accepts a function.

An example in this library is [`Maybe`](index.html#returns.maybe.Maybe "returns.maybe.Maybe"),

that implements the `Mappable` interface:

```

>>> from returns.maybe import Maybe, Some

>>> def can\_be\_mapped(string: str) -> str:

...     return string + '!'

>>> maybe\_str: Maybe[str] = Some('example')

>>> assert maybe\_str.map(can\_be\_mapped) == Some('example!')

```

[`MappableN`](#returns.interfaces.mappable.MappableN "returns.interfaces.mappable.MappableN") interface helps us to

create our own mappable container like [`Maybe`](index.html#returns.maybe.Maybe "returns.maybe.Maybe").

```

>>> from typing import Callable, TypeVar

>>> from returns.interfaces.mappable import Mappable1

>>> from returns.primitives.hkt import SupportsKind1

>>> from returns.primitives.container import BaseContainer

>>> \_NumberType = TypeVar('\_NumberType')

>>> \_NewNumberType = TypeVar('\_NewNumberType')

>>> class Number(

...     BaseContainer,

...     SupportsKind1['Number', \_NumberType],

...     Mappable1[\_NumberType],

... ):

...     def \_\_init\_\_(self, inner\_value: \_NumberType) -> None:

...         super().\_\_init\_\_(inner\_value)

...

...     def map(  # This method is required by Mappable

...         self,

...         function: Callable[[\_NumberType], \_NewNumberType]

...     ) -> 'Number[\_NewNumberType]':

...         return Number(function(self.\_inner\_value))

```

With our `Number` mappable class we can compose easily math functions with it.

```

>>> def my\_math\_function(number: int) -> int:

...     return number - 1

>>> number: Number[int] = Number(-41)

>>> assert number.map(my\_math\_function).map(abs) == Number(42)

```

#### Laws[¶](#id2 "Permalink to this heading")

To make sure your `Mappable` implementation is right,

you can apply the `Mappable` laws on it to test.

1. [`Identity Law`](#returns.interfaces.mappable._LawSpec.identity_law "returns.interfaces.mappable._LawSpec.identity_law"):

When we pass the identity function to the `map` method,

the `Mappable` instance has to be the same, unchanged.

```

>>> from returns.functions import identity

>>> mappable\_number: Number[int] = Number(1)

>>> assert mappable\_number.map(identity) == Number(1)

```

2. [`Associative Law`](#returns.interfaces.mappable._LawSpec.associative_law "returns.interfaces.mappable._LawSpec.associative_law"):

Given two functions, `x` and `y`,

calling the map method with `x` function and after that calling

with `y` function must have the

same result if we compose them together.

```

>>> from returns.functions import compose

>>> def add\_one(number: int) -> int:

...     return number + 1

>>> def multiply\_by\_ten(number: int) -> int:

...     return number \* 10

>>> mappable\_number: Number[int] = Number(9)

>>> assert mappable\_number.map(

...    add\_one,

... ).map(

...    multiply\_by\_ten,

... ) == mappable\_number.map(

...     compose(add\_one, multiply\_by\_ten),

... )

```

### Bindable[¶](#bindable "Permalink to this heading")

Bindable is something that we can bind with a function. Like

[`Maybe`](index.html#returns.maybe.Maybe "returns.maybe.Maybe"), so

[`BindableN`](#returns.interfaces.bindable.BindableN "returns.interfaces.bindable.BindableN") interface will help

us to create our custom bindable.

```

>>> from typing import Callable, TypeVar

>>> from returns.interfaces.bindable import Bindable1

>>> from returns.primitives.hkt import SupportsKind1, Kind1, dekind

>>> from returns.primitives.container import BaseContainer

>>> \_NumberType = TypeVar('\_NumberType')

>>> \_NewNumberType = TypeVar('\_NewNumberType')

>>> class Number(

...     BaseContainer,

...     SupportsKind1['Number', \_NumberType],

...     Bindable1[\_NumberType],

... ):

...     def \_\_init\_\_(self, inner\_value: \_NumberType) -> None:

...         super().\_\_init\_\_(inner\_value)

...

...     def bind(  # This method is required by Bindable

...         self,

...         function: Kind1[

...             'Number',

...             Callable[[\_NumberType], 'Number[\_NewNumberType]'],

...         ],

...     ) -> 'Number[\_NewNumberType]':

...         return dekind(function(self.\_inner\_value))

```

And here’s how we can use it:

```

>>> def double(arg: int) -> Number[int]:

...    return Number(arg \* 2)

>>> number = Number(5)

>>> assert number.bind(double) == Number(10)

```

### Applicative[¶](#applicative "Permalink to this heading")

Something is considered applicative

if it is a functor already and,

moreover, we can `apply` another container to it

and construct a new value with `.from\_value` method.

An example in this library is [`Maybe`](index.html#returns.maybe.Maybe "returns.maybe.Maybe"),

that implements the `Mappable` and `Applicative` interfaces:

```

>>> from returns.maybe import Maybe, Some

>>> maybe\_str = Maybe.from\_value('example')

>>> maybe\_func = Maybe.from\_value(len)  # we use function as a value!

>>> assert maybe\_str.apply(maybe\_func) == Some(7)

```

As you see, `apply` takes a container with a function inside

and applies it to the current value inside the container.

This way we really execute `Maybe.from\_value(len('example'))`.

[`ApplicativeN`](#returns.interfaces.applicative.ApplicativeN "returns.interfaces.applicative.ApplicativeN") which is a subtype of

[`MappableN`](#returns.interfaces.mappable.MappableN "returns.interfaces.mappable.MappableN") interface helps us to

create our own applicative container like [`Maybe`](index.html#returns.maybe.Maybe "returns.maybe.Maybe").

```

>>> from typing import Callable, TypeVar

>>> from returns.interfaces.applicative import Applicative1

>>> from returns.primitives.hkt import SupportsKind1, Kind1, dekind

>>> from returns.primitives.container import BaseContainer

>>> \_NumberType = TypeVar('\_NumberType')

>>> \_NewNumberType = TypeVar('\_NewNumberType')

>>> class Number(

...     BaseContainer,

...     SupportsKind1['Number', \_NumberType],

...     Applicative1[\_NumberType],

... ):

...     def \_\_init\_\_(self, inner\_value: \_NumberType) -> None:

...         super().\_\_init\_\_(inner\_value)

...

...     def map(  # This method is required by Mappable

...         self,

...         function: Callable[[\_NumberType], \_NewNumberType]

...     ) -> 'Number[\_NewNumberType]':

...         return Number(function(self.\_inner\_value))

...

...     def apply(  # This method is required by Applicative

...         self,

...         container: Kind1[

...             'Number',

...             Callable[[\_NumberType], \_NewNumberType],

...         ],

...     ) -> 'Number[\_NewNumberType]':

...         return Number.from\_value(

...             dekind(container.\_inner\_value(self.\_inner\_value)),

...         )

...

...     @classmethod

...     def from\_value(  # This method is required by Applicative

...         cls,

...         inner\_value: \_NewNumberType,

...     ) -> 'Number[\_NewNumberType]':

...         return Number(inner\_value)

```

With our `Number` mappable class we can compose easily math functions with it.

```

>>> def my\_math\_function(number: int) -> int:

...     return number - 1

>>> number = Number(3)

>>> number\_function = Number.from\_value(my\_math\_function)

>>> assert number.apply(number\_function) == Number(2)

```

#### Laws[¶](#id3 "Permalink to this heading")

To make sure your `Applicative` implementation is right,

you can apply the `Applicative` laws on it to test.

1. [`Identity Law`](#returns.interfaces.applicative._LawSpec.identity_law "returns.interfaces.applicative._LawSpec.identity_law"):

When we pass an applicative instance

with wrapped identity function to the `apply` method,

the `Applicative` has to be the same, unchanged.

```

>>> from returns.functions import identity

>>> applicative\_number: Number[int] = Number(1)

>>> assert applicative\_number.apply(

...     applicative\_number.from\_value(identity),

... ) == Number(1)

```

2. [`Interchange Law`](#returns.interfaces.applicative._LawSpec.interchange_law "returns.interfaces.applicative._LawSpec.interchange_law"):

We can start our composition with both raw value and a function.

```

>>> def function(arg: int) -> int:

...     return arg + 1

>>> raw\_value = 5

>>> assert Number.from\_value(raw\_value).apply(

...     Number.from\_value(function),

... ) == Number.from\_value(function).apply(

...     Number.from\_value(lambda inner: inner(raw\_value)),

... )

```

3. [`Homomorphism Law`](#returns.interfaces.applicative._LawSpec.homomorphism_law "returns.interfaces.applicative._LawSpec.homomorphism_law"):

The homomorphism law says that

applying a wrapped function to a wrapped value is the same

as applying the function to the value in the normal way

and then using `.from\_value` on the result.

```

>>> def function(arg: int) -> int:

...     return arg + 1

>>> raw\_value = 5

>>> assert Number.from\_value(

...     function(raw\_value),

... ) == Number.from\_value(raw\_value).apply(

...     Number.from\_value(function),

... )

```

4. [`Composition Law`](#returns.interfaces.applicative._LawSpec.composition_law "returns.interfaces.applicative._LawSpec.composition_law"):

Applying two functions twice is the same

as applying their composition once.

```

>>> from returns.functions import compose

>>> def first(arg: int) -> int:

...     return arg \* 2

>>> def second(arg: int) -> int:

...     return arg + 1

>>> instance = Number(5)

>>> assert instance.apply(

...     Number.from\_value(compose(first, second)),

... ) == instance.apply(

...     Number.from\_value(first),

... ).apply(

...     Number.from\_value(second),

... )

```

Plus all laws from `MappableN` interface.

### Container[¶](#container "Permalink to this heading")

[`ContainerN`](#returns.interfaces.container.ContainerN "returns.interfaces.container.ContainerN") is a central piece of our library.

It is an interface that combines

[`ApplicativeN`](#returns.interfaces.applicative.ApplicativeN "returns.interfaces.applicative.ApplicativeN")

and

[`BindableN`](#returns.interfaces.bindable.BindableN "returns.interfaces.bindable.BindableN") together.

So, in other words: `Container` is an `Apllicative` that you can `bind`!

```

>>> from typing import Callable, TypeVar

>>> from returns.interfaces.container import Container1

>>> from returns.primitives.hkt import SupportsKind1, Kind1, dekind

>>> from returns.primitives.container import BaseContainer

>>> \_NumberType = TypeVar('\_NumberType')

>>> \_NewNumberType = TypeVar('\_NewNumberType')

>>> class Number(

...     BaseContainer,

...     SupportsKind1['Number', \_NumberType],

...     Container1[\_NumberType],

... ):

...     def \_\_init\_\_(self, inner\_value: \_NumberType) -> None:

...         super().\_\_init\_\_(inner\_value)

...

...     def map(  # This method is required by Mappable

...         self,

...         function: Callable[[\_NumberType], \_NewNumberType]

...     ) -> 'Number[\_NewNumberType]':

...         return Number(function(self.\_inner\_value))

...

...     def bind(  # This method is required by Bindable

...         self,

...         function: Kind1[

...             'Number',

...             Callable[[\_NumberType], 'Number[\_NewNumberType]'],

...         ],

...     ) -> 'Number[\_NewNumberType]':

...         return dekind(function(self.\_inner\_value))

...

...     def apply(  # This method is required by Applicative

...         self,

...         container: Kind1[

...             'Number',

...             Callable[[\_NumberType], \_NewNumberType],

...         ],

...     ) -> 'Number[\_NewNumberType]':

...         return Number.from\_value(

...             container.\_inner\_value(self.\_inner\_value),

...         )

...

...     @classmethod

...     def from\_value(  # This method is required by Applicative

...         cls,

...         inner\_value: \_NewNumberType,

...     ) -> 'Number[\_NewNumberType]':

...         return Number(inner\_value)

```

This code gives us an opportunity to use `Number`

with `map`, `apply`, and `bind` as we already did in the examples above.

#### Laws[¶](#id4 "Permalink to this heading")

To make sure other people will be able to use your implementation, it should

respect three new laws.

1. [`Left Identity`](#returns.interfaces.container._LawSpec.left_identity_law "returns.interfaces.container._LawSpec.left_identity_law"):

If we `bind` a function to our bindable must have to be

the same result as passing the value directly to the function.

```

>>> def can\_be\_bound(value: int) -> Number[int]:

...     return Number(value)

>>> assert Number.from\_value(5).bind(can\_be\_bound) == can\_be\_bound(5)

```

2. [`Right Identity`](#returns.interfaces.container._LawSpec.right_identity_law "returns.interfaces.container._LawSpec.right_identity_law"):

If we pass the bindable constructor through `bind` must

have to be the same result as instantiating the bindable on our own.

```

>>> number = Number(2)

>>> assert number.bind(Number) == Number(2)

```

3. [`Associative Law`](#returns.interfaces.container._LawSpec.associative_law "returns.interfaces.container._LawSpec.associative_law"):

Given two functions, `x` and `y`, calling the bind

method with `x` function and after that calling with `y` function

must have the same result if we bind with

a function that passes the value to `x`

and then bind the result with `y`.

```

>>> def minus\_one(arg: int) -> Number[int]:

...     return Number(arg - 1)

>>> def half(arg: int) -> Number[int]:

...     return Number(arg // 2)

>>> number = Number(9)

>>> assert number.bind(minus\_one).bind(half) == number.bind(

...    lambda value: minus\_one(value).bind(half),

... )

```

Plus all laws from `MappableN` and `ApplicativeN` interfaces.

### More![¶](#more "Permalink to this heading")

We have way more interfaces with different features!

We have covered all of them in the technical docs.

So, use them to enforce type-safety of your own containers.

#### Specific interfaces[¶](#specific-interfaces "Permalink to this heading")

We also have a whole package of different specific interfaces

that will help you to create containers based on our internal types,

like `Result`.

### FAQ[¶](#faq "Permalink to this heading")

#### Why do you have general and specific interfaces?[¶](#why-do-you-have-general-and-specific-interfaces "Permalink to this heading")

We have `.interfaces.\*` types that can be applied to any possible type.

There’s nothing they know about other types or `returns` package.

We also have a special `.interfaces.specific` package

where we have types that know about other types in `returns`.

For example, `MappableN` from `.interfaces`

only knows about `.map` method. It does not require anything else.

But, `ResultLikeN` from `.interfaces.specific.result`

does require to have `.bind\_result` method

which relies on our [`Result`](index.html#returns.result.Result "returns.result.Result") type.

That’s the only difference.

Build your own types with any of those interfaces.

#### Why some interfaces do not have type alias for 1 or 2 type arguments?[¶](#why-some-interfaces-do-not-have-type-alias-for-1-or-2-type-arguments "Permalink to this heading")

Some types like

[`ResultLikeN`](#returns.interfaces.specific.result.ResultLikeN "returns.interfaces.specific.result.ResultLikeN")

do not have type aliases for one type argument in a form of `ResultLike1`.

Why does `Mappable1` exists and `ResultLike1` does not?

Because `Mappable1` does make sense.

But, `ResultLike1` requires at least two (value and error) types to exist.

The same applies for `ReaderLike1` and `ReaderResultLike1`

and `ReaderResultLike2`.

We don’t support type aliases for types that won’t make sense.

#### What’s the difference between `MappableN` and `BindableN`?[¶](#what-s-the-difference-between-mappablen-and-bindablen "Permalink to this heading")

While `MappableN` you have to pass a pure function, like:

```

>>> def can\_be\_mapped(string: str) -> str:

...     return string

```

with Bindable we have to pass a function that returns another container:

```

>>> from returns.maybe import Maybe

>>> def can\_be\_bound(string: str) -> Maybe[str]:

...     return Some(string + '!')

```

The main difference is the return type.

The consequence of this is big!

`BindableN` allows to change the container type.

While `MappableN` cannot do that.

So, `Some.bind(function)` can be evaluated to both `Some` and `Nothing`.

While `Some.map(function)` will always stay as `Some`.

#### What is the difference between ResultLikeN and ResultBasedN?[¶](#what-is-the-difference-between-resultliken-and-resultbasedn "Permalink to this heading")

`ResultLikeN` is just an intention of having a result

(e.g. [`FutureResult`](index.html#returns.future.FutureResult "returns.future.FutureResult")),

it’s not the result yet. While `ResultBasedN` is a concrete result

(e.g. [`IOResult`](index.html#returns.io.IOResult "returns.io.IOResult")),

it has the desired result value.

Because of this difference between them is why we can’t unwrap a `ResultLikeN`

container, it does not have the real result yet.

See the example below using `FutureResult` to get a `IOResult`:

```

>>> import anyio

>>> from returns.future import FutureResult

>>> from returns.interfaces.specific.future\_result import FutureResultBasedN

>>> from returns.interfaces.specific.ioresult import (

...    IOResultBasedN,

...    IOResultLikeN,

... )

>>> from returns.interfaces.specific.result import ResultLikeN, ResultBasedN

>>> from returns.io import IOSuccess, IOResult

>>> from returns.result import Success, Result

>>> async def coro(arg: int) -> Result[int, str]:

...     return Success(arg + 1)

>>> # `result\_like` does not have the result we want (Result[int, str])

>>> # it's just the intention of having one,

>>> # we have to await it to get the real result

>>> result\_like: FutureResult[int, str] = FutureResult(coro(1))

>>> assert isinstance(result\_like, FutureResultBasedN)

>>> assert isinstance(result\_like, IOResultLikeN)

>>> assert isinstance(result\_like, ResultLikeN)

>>> # `anyio.run(...)` will await our coroutine and give the real result to us

>>> result: IOResult[int, str] = anyio.run(result\_like.awaitable)

>>> assert isinstance(result, IOResultBasedN)

>>> assert isinstance(result, ResultLikeN)

>>> # Compare it with the real result:

>>> assert isinstance(Success(1), ResultBasedN)

```

Note

The same difference applies to all `\*ResultLikeN` vs `\*ResultBasedN`

(e.g. [`IOResultLikeN`](#returns.interfaces.specific.ioresult.IOResultLikeN "returns.interfaces.specific.ioresult.IOResultLikeN")

and [`IOResultBasedN`](#returns.interfaces.specific.ioresult.IOResultBasedN "returns.interfaces.specific.ioresult.IOResultBasedN"))

### API Reference[¶](#api-reference "Permalink to this heading")

#### Overview[¶](#overview "Permalink to this heading")

Here’s a full overview of all our interfaces:

 classDiagram

 AltableN <|-- BiMappableN

 ApplicativeN <|-- ContainerN

 AwaitableFutureN <|-- FutureBasedN

 BindableN <|-- ContainerN

 CallableReader2 <|-- ReaderBased2

 CallableReader3 <|-- ReaderFutureResultBasedN

 CallableReader3 <|-- ReaderIOResultBasedN

 CallableReader3 <|-- ReaderResultBasedN

 ContainerN <|-- FailableN

 ContainerN <|-- IOLikeN

 ContainerN <|-- ReaderLike2

 ContainerN <|-- ReaderLike3

 Contextable <|-- CallableReader2

 Contextable <|-- CallableReader3

 DiverseFailableN <|-- ResultLikeN

 Equable <|-- IOBasedN

 Equable <|-- MaybeBasedN

 Equable <|-- UnwrappableResult

 FailableN <|-- DiverseFailableN

 FailableN <|-- SingleFailableN

 FutureBasedN <|-- FutureResultBasedN

 FutureLikeN <|-- FutureBasedN

 FutureLikeN <|-- FutureResultLikeN

 FutureResultLikeN <|-- FutureResultBasedN

 FutureResultLikeN <|-- ReaderFutureResultLikeN

 Generic <|-- AwaitableFutureN

 Generic <|-- BindableN

 Generic <|-- Contextable

 Generic <|-- LashableN

 Generic <|-- Unwrappable

 IOBasedN <|-- IOResultBasedN

 IOLikeN <|-- FutureLikeN

 IOLikeN <|-- IOBasedN

 IOLikeN <|-- IOResultLikeN

 IOResultLikeN <|-- FutureResultLikeN

 IOResultLikeN <|-- IOResultBasedN

 IOResultLikeN <|-- ReaderIOResultLikeN

 LashableN <|-- FailableN

 LawSpecDef <|-- \_DiverseFailableLawSpec

 LawSpecDef <|-- \_FailableLawSpec

 LawSpecDef <|-- \_LawSpec

 LawSpecDef <|-- \_SingleFailableLawSpec

 Lawful <|-- AltableN

 Lawful <|-- ApplicativeN

 Lawful <|-- ContainerN

 Lawful <|-- DiverseFailableN

 Lawful <|-- FailableN

 Lawful <|-- MappableN

 Lawful <|-- MaybeLikeN

 Lawful <|-- ReaderBased2

 Lawful <|-- ReaderFutureResultBasedN

 Lawful <|-- ReaderIOResultBasedN

 Lawful <|-- ReaderResultBasedN

 MappableN <|-- ApplicativeN

 MappableN <|-- BiMappableN

 MaybeLikeN <|-- MaybeBasedN

 ReaderFutureResultLikeN <|-- ReaderFutureResultBasedN

 ReaderIOResultLikeN <|-- ReaderFutureResultLikeN

 ReaderIOResultLikeN <|-- ReaderIOResultBasedN

 ReaderLike2 <|-- CallableReader2

 ReaderLike3 <|-- CallableReader3

 ReaderLike3 <|-- ReaderResultLikeN

 ReaderResultLikeN <|-- ReaderIOResultLikeN

 ReaderResultLikeN <|-- ReaderResultBasedN

 ResultLikeN <|-- IOResultLikeN

 ResultLikeN <|-- ReaderResultLikeN

 ResultLikeN <|-- UnwrappableResult

 SingleFailableN <|-- MaybeLikeN

 SwappableN <|-- DiverseFailableN

 Unwrappable <|-- MaybeBasedN

 Unwrappable <|-- UnwrappableResult

 UnwrappableResult <|-- IOResultBasedN

 UnwrappableResult <|-- ResultBasedN

 Let’s review it one by one.

#### Equable[¶](#equable "Permalink to this heading")

 classDiagram

 LawSpecDef <|-- \_LawSpec

 Lawful <|-- Equable

 

*final class* \_LawSpec[[source]](_modules/returns/interfaces/equable.html#_LawSpec)[¶](#returns.interfaces.equable._LawSpec "Permalink to this definition")

Bases: [`LawSpecDef`](index.html#returns.primitives.laws.LawSpecDef "returns.primitives.laws.LawSpecDef")

Equality laws.

Description: <https://bit.ly/34D40iT>

*static* reflexive\_law(*first*)[[source]](_modules/returns/interfaces/equable.html#_LawSpec.reflexive_law)[¶](#returns.interfaces.equable._LawSpec.reflexive_law "Permalink to this definition")

Value should be equal to itself.

Parameters:

**first** (`TypeVar`(`\_EqualType`, bound= Equable)) – 

Return type:

`None`

*static* symmetry\_law(*first*, *second*)[[source]](_modules/returns/interfaces/equable.html#_LawSpec.symmetry_law)[¶](#returns.interfaces.equable._LawSpec.symmetry_law "Permalink to this definition")

If `A == B` then `B == A`.

Parameters:

* **first** (`TypeVar`(`\_EqualType`, bound= Equable)) –

* **second** (`TypeVar`(`\_EqualType`, bound= Equable)) –

Return type:

`None`

*static* transitivity\_law(*first*, *second*, *third*)[[source]](_modules/returns/interfaces/equable.html#_LawSpec.transitivity_law)[¶](#returns.interfaces.equable._LawSpec.transitivity_law "Permalink to this definition")

If `A == B` and `B == C` then `A == C`.

Parameters:

* **first** (`TypeVar`(`\_EqualType`, bound= Equable)) –

* **second** (`TypeVar`(`\_EqualType`, bound= Equable)) –

* **third** (`TypeVar`(`\_EqualType`, bound= Equable)) –

Return type:

`None`

*class* Equable[[source]](_modules/returns/interfaces/equable.html#Equable)[¶](#returns.interfaces.equable.Equable "Permalink to this definition")

Bases: [`Lawful`](index.html#returns.primitives.laws.Lawful "returns.primitives.laws.Lawful")[[`Equable`](#returns.interfaces.equable.Equable "returns.interfaces.equable.Equable")]

Interface for types that can be compared with real values.

Not all types can, because some don’t have the value at a time:

- `Future` has to be awaited to get the value

- `Reader` has to be called to get the value

\_laws*: `ClassVar`[`Sequence`[[`Law`](index.html#returns.primitives.laws.Law "returns.primitives.laws.Law")]]* *= (<returns.primitives.laws.Law1 object>, <returns.primitives.laws.Law2 object>, <returns.primitives.laws.Law3 object>)*[¶](#returns.interfaces.equable.Equable._laws "Permalink to this definition")

Some classes and interfaces might have laws, some might not have any.

*abstract* equals(*other*)[[source]](_modules/returns/interfaces/equable.html#Equable.equals)[¶](#returns.interfaces.equable.Equable.equals "Permalink to this definition")

Type-safe equality check for values of the same type.

Parameters:

* **self** (`TypeVar`(`\_EqualType`, bound= Equable)) –

* **other** (`TypeVar`(`\_EqualType`, bound= Equable)) –

Return type:

`bool`

#### Mappable[¶](#id5 "Permalink to this heading")

 classDiagram

 LawSpecDef <|-- \_LawSpec

 Lawful <|-- MappableN

 

*final class* \_LawSpec[[source]](_modules/returns/interfaces/mappable.html#_LawSpec)[¶](#returns.interfaces.mappable._LawSpec "Permalink to this definition")

Bases: [`LawSpecDef`](index.html#returns.primitives.laws.LawSpecDef "returns.primitives.laws.LawSpecDef")

Mappable or functor laws.

<https://en.wikibooks.org/wiki/Haskell/The_Functor_class#The_functor_laws>

*static* identity\_law(*mappable*)[[source]](_modules/returns/interfaces/mappable.html#_LawSpec.identity_law)[¶](#returns.interfaces.mappable._LawSpec.identity_law "Permalink to this definition")

Mapping identity over a value must return the value unchanged.

Parameters:

**mappable** ([`MappableN`](#returns.interfaces.mappable.MappableN "returns.interfaces.mappable.MappableN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) – 

Return type:

`None`

*static* associative\_law(*mappable*, *first*, *second*)[[source]](_modules/returns/interfaces/mappable.html#_LawSpec.associative_law)[¶](#returns.interfaces.mappable._LawSpec.associative_law "Permalink to this definition")

Mapping twice or mapping a composition is the same thing.

Parameters:

* **mappable** ([`MappableN`](#returns.interfaces.mappable.MappableN "returns.interfaces.mappable.MappableN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) –

* **first** (`Callable`[[`TypeVar`(`\_FirstType`)], `TypeVar`(`\_NewType1`)]) –

* **second** (`Callable`[[`TypeVar`(`\_NewType1`)], `TypeVar`(`\_NewType2`)]) –

Return type:

`None`

*class* MappableN[[source]](_modules/returns/interfaces/mappable.html#MappableN)[¶](#returns.interfaces.mappable.MappableN "Permalink to this definition")

Bases: `Generic`[`\_FirstType`, `\_SecondType`, `\_ThirdType`], [`Lawful`](index.html#returns.primitives.laws.Lawful "returns.primitives.laws.Lawful")[`MappableN[\_FirstType, \_SecondType, \_ThirdType]`]

Allows to chain wrapped values in containers with regular functions.

Behaves like a functor.

See also

* <https://en.wikipedia.org/wiki/Functor>

\_laws*: `ClassVar`[`Sequence`[[`Law`](index.html#returns.primitives.laws.Law "returns.primitives.laws.Law")]]* *= (<returns.primitives.laws.Law1 object>, <returns.primitives.laws.Law3 object>)*[¶](#returns.interfaces.mappable.MappableN._laws "Permalink to this definition")

Some classes and interfaces might have laws, some might not have any.

*abstract* map(*function*)[[source]](_modules/returns/interfaces/mappable.html#MappableN.map)[¶](#returns.interfaces.mappable.MappableN.map "Permalink to this definition")

Allows to run a pure function over a container.

Parameters:

* **self** (`TypeVar`(`\_MappableType`, bound= MappableN)) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], `TypeVar`(`\_UpdatedType`)]) –

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_MappableType`, bound= MappableN), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

Mappable1[¶](#returns.interfaces.mappable.Mappable1 "Permalink to this definition")

Type alias for kinds with one type argument.

alias of [`MappableN`](#returns.interfaces.mappable.MappableN "returns.interfaces.mappable.MappableN")[`\_FirstType`, `NoReturn`, `NoReturn`]

Mappable2[¶](#returns.interfaces.mappable.Mappable2 "Permalink to this definition")

Type alias for kinds with two type arguments.

alias of [`MappableN`](#returns.interfaces.mappable.MappableN "returns.interfaces.mappable.MappableN")[`\_FirstType`, `\_SecondType`, `NoReturn`]

Mappable3[¶](#returns.interfaces.mappable.Mappable3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`MappableN`](#returns.interfaces.mappable.MappableN "returns.interfaces.mappable.MappableN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

#### Bindable[¶](#id6 "Permalink to this heading")

 classDiagram

 Generic <|-- BindableN

 

*class* BindableN[[source]](_modules/returns/interfaces/bindable.html#BindableN)[¶](#returns.interfaces.bindable.BindableN "Permalink to this definition")

Bases: `Generic`[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

Represents a “context” in which calculations can be executed.

`Bindable` allows you to bind together

a series of calculations while maintaining

the context of that specific container.

In contrast to [`returns.interfaces.lashable.LashableN`](#returns.interfaces.lashable.LashableN "returns.interfaces.lashable.LashableN"),

works with the first type argument.

*abstract* bind(*function*)[[source]](_modules/returns/interfaces/bindable.html#BindableN.bind)[¶](#returns.interfaces.bindable.BindableN.bind "Permalink to this definition")

Applies ‘function’ to the result of a previous calculation.

And returns a new container.

Parameters:

* **self** (`TypeVar`(`\_BindableType`, bound= BindableN)) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_BindableType`, bound= BindableN), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]) –

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_BindableType`, bound= BindableN), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

Bindable1[¶](#returns.interfaces.bindable.Bindable1 "Permalink to this definition")

Type alias for kinds with one type argument.

alias of [`BindableN`](#returns.interfaces.bindable.BindableN "returns.interfaces.bindable.BindableN")[`\_FirstType`, `NoReturn`, `NoReturn`]

Bindable2[¶](#returns.interfaces.bindable.Bindable2 "Permalink to this definition")

Type alias for kinds with two type arguments.

alias of [`BindableN`](#returns.interfaces.bindable.BindableN "returns.interfaces.bindable.BindableN")[`\_FirstType`, `\_SecondType`, `NoReturn`]

Bindable3[¶](#returns.interfaces.bindable.Bindable3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`BindableN`](#returns.interfaces.bindable.BindableN "returns.interfaces.bindable.BindableN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

#### Applicative[¶](#id7 "Permalink to this heading")

 classDiagram

 LawSpecDef <|-- \_LawSpec

 Lawful <|-- ApplicativeN

 MappableN <|-- ApplicativeN

 

*final class* \_LawSpec[[source]](_modules/returns/interfaces/applicative.html#_LawSpec)[¶](#returns.interfaces.applicative._LawSpec "Permalink to this definition")

Bases: [`LawSpecDef`](index.html#returns.primitives.laws.LawSpecDef "returns.primitives.laws.LawSpecDef")

Applicative mappable laws.

Definition: <https://bit.ly/3hC8F8E>

Discussion: <https://bit.ly/3jffz3L>

*static* identity\_law(*container*)[[source]](_modules/returns/interfaces/applicative.html#_LawSpec.identity_law)[¶](#returns.interfaces.applicative._LawSpec.identity_law "Permalink to this definition")

Identity law.

If we apply wrapped `identity` function to a container,

nothing happens.

Parameters:

**container** ([`ApplicativeN`](#returns.interfaces.applicative.ApplicativeN "returns.interfaces.applicative.ApplicativeN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) – 

Return type:

`None`

*static* interchange\_law(*raw\_value*, *container*, *function*)[[source]](_modules/returns/interfaces/applicative.html#_LawSpec.interchange_law)[¶](#returns.interfaces.applicative._LawSpec.interchange_law "Permalink to this definition")

Interchange law.

Basically we check that we can start our composition

with both `raw\_value` and `function`.

Great explanation: <https://stackoverflow.com/q/27285918/4842742>

Parameters:

* **raw\_value** (`TypeVar`(`\_FirstType`)) –

* **container** ([`ApplicativeN`](#returns.interfaces.applicative.ApplicativeN "returns.interfaces.applicative.ApplicativeN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], `TypeVar`(`\_NewType1`)]) –

Return type:

`None`

*static* homomorphism\_law(*raw\_value*, *container*, *function*)[[source]](_modules/returns/interfaces/applicative.html#_LawSpec.homomorphism_law)[¶](#returns.interfaces.applicative._LawSpec.homomorphism_law "Permalink to this definition")

Homomorphism law.

The homomorphism law says that

applying a wrapped function to a wrapped value is the same

as applying the function to the value in the normal way

and then using `.from\_value` on the result.

Parameters:

* **raw\_value** (`TypeVar`(`\_FirstType`)) –

* **container** ([`ApplicativeN`](#returns.interfaces.applicative.ApplicativeN "returns.interfaces.applicative.ApplicativeN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], `TypeVar`(`\_NewType1`)]) –

Return type:

`None`

*static* composition\_law(*container*, *first*, *second*)[[source]](_modules/returns/interfaces/applicative.html#_LawSpec.composition_law)[¶](#returns.interfaces.applicative._LawSpec.composition_law "Permalink to this definition")

Composition law.

Applying two functions twice is the same

as applying their composition once.

Parameters:

* **container** ([`ApplicativeN`](#returns.interfaces.applicative.ApplicativeN "returns.interfaces.applicative.ApplicativeN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) –

* **first** (`Callable`[[`TypeVar`(`\_FirstType`)], `TypeVar`(`\_NewType1`)]) –

* **second** (`Callable`[[`TypeVar`(`\_NewType1`)], `TypeVar`(`\_NewType2`)]) –

Return type:

`None`

*class* ApplicativeN[[source]](_modules/returns/interfaces/applicative.html#ApplicativeN)[¶](#returns.interfaces.applicative.ApplicativeN "Permalink to this definition")

Bases: [`MappableN`](#returns.interfaces.mappable.MappableN "returns.interfaces.mappable.MappableN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`], [`Lawful`](index.html#returns.primitives.laws.Lawful "returns.primitives.laws.Lawful")[`ApplicativeN[\_FirstType, \_SecondType, \_ThirdType]`]

Allows to create unit containers from raw values and to apply wrapped funcs.

See also

* <https://en.wikipedia.org/wiki/Applicative_functor>

* <http://learnyouahaskell.com/functors-applicative-functors-and-monoids>

\_laws*: `ClassVar`[`Sequence`[[`Law`](index.html#returns.primitives.laws.Law "returns.primitives.laws.Law")]]* *= (<returns.primitives.laws.Law1 object>, <returns.primitives.laws.Law3 object>, <returns.primitives.laws.Law3 object>, <returns.primitives.laws.Law3 object>)*[¶](#returns.interfaces.applicative.ApplicativeN._laws "Permalink to this definition")

Some classes and interfaces might have laws, some might not have any.

*abstract* apply(*container*)[[source]](_modules/returns/interfaces/applicative.html#ApplicativeN.apply)[¶](#returns.interfaces.applicative.ApplicativeN.apply "Permalink to this definition")

Allows to apply a wrapped function over a container.

Parameters:

* **self** (`TypeVar`(`\_ApplicativeType`, bound= ApplicativeN)) –

* **container** ([`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ApplicativeType`, bound= ApplicativeN), `Callable`[[`TypeVar`(`\_FirstType`)], `TypeVar`(`\_UpdatedType`)], `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) –

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ApplicativeType`, bound= ApplicativeN), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

*abstract classmethod* from\_value(*inner\_value*)[[source]](_modules/returns/interfaces/applicative.html#ApplicativeN.from_value)[¶](#returns.interfaces.applicative.ApplicativeN.from_value "Permalink to this definition")

Unit method to create new containers from any raw value.

Parameters:

**inner\_value** (`TypeVar`(`\_UpdatedType`)) – 

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ApplicativeType`, bound= ApplicativeN), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

Applicative1[¶](#returns.interfaces.applicative.Applicative1 "Permalink to this definition")

Type alias for kinds with one type argument.

alias of [`ApplicativeN`](#returns.interfaces.applicative.ApplicativeN "returns.interfaces.applicative.ApplicativeN")[`\_FirstType`, `NoReturn`, `NoReturn`]

Applicative2[¶](#returns.interfaces.applicative.Applicative2 "Permalink to this definition")

Type alias for kinds with two type arguments.

alias of [`ApplicativeN`](#returns.interfaces.applicative.ApplicativeN "returns.interfaces.applicative.ApplicativeN")[`\_FirstType`, `\_SecondType`, `NoReturn`]

Applicative3[¶](#returns.interfaces.applicative.Applicative3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`ApplicativeN`](#returns.interfaces.applicative.ApplicativeN "returns.interfaces.applicative.ApplicativeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

#### Altable[¶](#altable "Permalink to this heading")

 classDiagram

 LawSpecDef <|-- \_LawSpec

 Lawful <|-- AltableN

 

*final class* \_LawSpec[[source]](_modules/returns/interfaces/altable.html#_LawSpec)[¶](#returns.interfaces.altable._LawSpec "Permalink to this definition")

Bases: [`LawSpecDef`](index.html#returns.primitives.laws.LawSpecDef "returns.primitives.laws.LawSpecDef")

Mappable or functor laws.

<https://en.wikibooks.org/wiki/Haskell/The_Functor_class#The_functor_laws>

*static* identity\_law(*altable*)[[source]](_modules/returns/interfaces/altable.html#_LawSpec.identity_law)[¶](#returns.interfaces.altable._LawSpec.identity_law "Permalink to this definition")

Mapping identity over a value must return the value unchanged.

Parameters:

**altable** ([`AltableN`](#returns.interfaces.altable.AltableN "returns.interfaces.altable.AltableN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) – 

Return type:

`None`

*static* associative\_law(*altable*, *first*, *second*)[[source]](_modules/returns/interfaces/altable.html#_LawSpec.associative_law)[¶](#returns.interfaces.altable._LawSpec.associative_law "Permalink to this definition")

Mapping twice or mapping a composition is the same thing.

Parameters:

* **altable** ([`AltableN`](#returns.interfaces.altable.AltableN "returns.interfaces.altable.AltableN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) –

* **first** (`Callable`[[`TypeVar`(`\_SecondType`)], `TypeVar`(`\_NewType1`)]) –

* **second** (`Callable`[[`TypeVar`(`\_NewType1`)], `TypeVar`(`\_NewType2`)]) –

Return type:

`None`

*class* AltableN[[source]](_modules/returns/interfaces/altable.html#AltableN)[¶](#returns.interfaces.altable.AltableN "Permalink to this definition")

Bases: `Generic`[`\_FirstType`, `\_SecondType`, `\_ThirdType`], [`Lawful`](index.html#returns.primitives.laws.Lawful "returns.primitives.laws.Lawful")[`AltableN[\_FirstType, \_SecondType, \_ThirdType]`]

Modifies the second type argument with a pure function.

\_laws*: `ClassVar`[`Sequence`[[`Law`](index.html#returns.primitives.laws.Law "returns.primitives.laws.Law")]]* *= (<returns.primitives.laws.Law1 object>, <returns.primitives.laws.Law3 object>)*[¶](#returns.interfaces.altable.AltableN._laws "Permalink to this definition")

Some classes and interfaces might have laws, some might not have any.

*abstract* alt(*function*)[[source]](_modules/returns/interfaces/altable.html#AltableN.alt)[¶](#returns.interfaces.altable.AltableN.alt "Permalink to this definition")

Allows to run a pure function over a container.

Parameters:

* **self** (`TypeVar`(`\_AltableType`, bound= AltableN)) –

* **function** (`Callable`[[`TypeVar`(`\_SecondType`)], `TypeVar`(`\_UpdatedType`)]) –

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_AltableType`, bound= AltableN), `TypeVar`(`\_FirstType`), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_ThirdType`)]

Altable2[¶](#returns.interfaces.altable.Altable2 "Permalink to this definition")

Type alias for kinds with two type arguments.

alias of [`AltableN`](#returns.interfaces.altable.AltableN "returns.interfaces.altable.AltableN")[`\_FirstType`, `\_SecondType`, `NoReturn`]

Altable3[¶](#returns.interfaces.altable.Altable3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`AltableN`](#returns.interfaces.altable.AltableN "returns.interfaces.altable.AltableN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

#### BiMappable[¶](#bimappable "Permalink to this heading")

 classDiagram

 AltableN <|-- BiMappableN

 MappableN <|-- BiMappableN

 

*class* BiMappableN[[source]](_modules/returns/interfaces/bimappable.html#BiMappableN)[¶](#returns.interfaces.bimappable.BiMappableN "Permalink to this definition")

Bases: [`MappableN`](#returns.interfaces.mappable.MappableN "returns.interfaces.mappable.MappableN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`], [`AltableN`](#returns.interfaces.altable.AltableN "returns.interfaces.altable.AltableN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

Allows to change both types of a container at the same time.

Uses `.map` to change first type and `.alt` to change second type.

See also

* <https://typelevel.org/cats/typeclasses/bifunctor.html>

BiMappable2[¶](#returns.interfaces.bimappable.BiMappable2 "Permalink to this definition")

Type alias for kinds with two type arguments.

alias of [`BiMappableN`](#returns.interfaces.bimappable.BiMappableN "returns.interfaces.bimappable.BiMappableN")[`\_FirstType`, `\_SecondType`, `NoReturn`]

BiMappable3[¶](#returns.interfaces.bimappable.BiMappable3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`BiMappableN`](#returns.interfaces.bimappable.BiMappableN "returns.interfaces.bimappable.BiMappableN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

#### Swappable[¶](#swappable "Permalink to this heading")

 classDiagram

 BiMappableN <|-- SwappableN

 LawSpecDef <|-- \_LawSpec

 Lawful <|-- SwappableN

 

*final class* \_LawSpec[[source]](_modules/returns/interfaces/swappable.html#_LawSpec)[¶](#returns.interfaces.swappable._LawSpec "Permalink to this definition")

Bases: [`LawSpecDef`](index.html#returns.primitives.laws.LawSpecDef "returns.primitives.laws.LawSpecDef")

Laws for [`SwappableN`](#returns.interfaces.swappable.SwappableN "returns.interfaces.swappable.SwappableN") type.

*static* double\_swap\_law(*container*)[[source]](_modules/returns/interfaces/swappable.html#_LawSpec.double_swap_law)[¶](#returns.interfaces.swappable._LawSpec.double_swap_law "Permalink to this definition")

Swaaping container twice.

It ensure that we get the initial value back.

In other words, swapping twice does nothing.

Parameters:

**container** ([`SwappableN`](#returns.interfaces.swappable.SwappableN "returns.interfaces.swappable.SwappableN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) – 

Return type:

`None`

*class* SwappableN[[source]](_modules/returns/interfaces/swappable.html#SwappableN)[¶](#returns.interfaces.swappable.SwappableN "Permalink to this definition")

Bases: [`BiMappableN`](#returns.interfaces.bimappable.BiMappableN "returns.interfaces.bimappable.BiMappableN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`], [`Lawful`](index.html#returns.primitives.laws.Lawful "returns.primitives.laws.Lawful")[`SwappableN[\_FirstType, \_SecondType, \_ThirdType]`]

Interface that allows swapping first and second type values.

\_laws*: `ClassVar`[`Sequence`[[`Law`](index.html#returns.primitives.laws.Law "returns.primitives.laws.Law")]]* *= (<returns.primitives.laws.Law1 object>,)*[¶](#returns.interfaces.swappable.SwappableN._laws "Permalink to this definition")

Some classes and interfaces might have laws, some might not have any.

*abstract* swap()[[source]](_modules/returns/interfaces/swappable.html#SwappableN.swap)[¶](#returns.interfaces.swappable.SwappableN.swap "Permalink to this definition")

Swaps first and second types in `SwappableN`.

Parameters:

**self** (`TypeVar`(`\_SwappableType`, bound= SwappableN)) – 

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_SwappableType`, bound= SwappableN), `TypeVar`(`\_SecondType`), `TypeVar`(`\_FirstType`), `TypeVar`(`\_ThirdType`)]

Swappable2[¶](#returns.interfaces.swappable.Swappable2 "Permalink to this definition")

Type alias for kinds with two type arguments.

alias of [`SwappableN`](#returns.interfaces.swappable.SwappableN "returns.interfaces.swappable.SwappableN")[`\_FirstType`, `\_SecondType`, `NoReturn`]

Swappable3[¶](#returns.interfaces.swappable.Swappable3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`SwappableN`](#returns.interfaces.swappable.SwappableN "returns.interfaces.swappable.SwappableN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

#### Lashable[¶](#lashable "Permalink to this heading")

 classDiagram

 Generic <|-- LashableN

 

*class* LashableN[[source]](_modules/returns/interfaces/lashable.html#LashableN)[¶](#returns.interfaces.lashable.LashableN "Permalink to this definition")

Bases: `Generic`[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

Represents a “context” in which calculations can be executed.

`Rescueable` allows you to bind together

a series of calculations while maintaining

the context of that specific container.

In contrast to `returns.interfaces.bindable.BinbdaleN`,

works with the second type value.

*abstract* lash(*function*)[[source]](_modules/returns/interfaces/lashable.html#LashableN.lash)[¶](#returns.interfaces.lashable.LashableN.lash "Permalink to this definition")

Applies ‘function’ to the result of a previous calculation.

And returns a new container.

Parameters:

* **self** (`TypeVar`(`\_LashableType`, bound= LashableN)) –

* **function** (`Callable`[[`TypeVar`(`\_SecondType`)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_LashableType`, bound= LashableN), `TypeVar`(`\_FirstType`), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_ThirdType`)]]) –

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_LashableType`, bound= LashableN), `TypeVar`(`\_FirstType`), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_ThirdType`)]

Lashable2[¶](#returns.interfaces.lashable.Lashable2 "Permalink to this definition")

Type alias for kinds with two type arguments.

alias of [`LashableN`](#returns.interfaces.lashable.LashableN "returns.interfaces.lashable.LashableN")[`\_FirstType`, `\_SecondType`, `NoReturn`]

Lashable3[¶](#returns.interfaces.lashable.Lashable3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`LashableN`](#returns.interfaces.lashable.LashableN "returns.interfaces.lashable.LashableN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

#### Unwrappable[¶](#unwrappable "Permalink to this heading")

 classDiagram

 Generic <|-- Unwrappable

 

*class* Unwrappable[[source]](_modules/returns/interfaces/unwrappable.html#Unwrappable)[¶](#returns.interfaces.unwrappable.Unwrappable "Permalink to this definition")

Bases: `Generic`[`\_FirstType`, `\_SecondType`]

Represents containers that can unwrap and return its wrapped value.

There are no aliases or `UnwrappableN` for `Unwrappable` interface.

Because it always uses two and just two types.

Not all types can be `Unwrappable` because we do require

to raise `UnwrapFailedError` if unwrap is not possible.

*abstract* unwrap()[[source]](_modules/returns/interfaces/unwrappable.html#Unwrappable.unwrap)[¶](#returns.interfaces.unwrappable.Unwrappable.unwrap "Permalink to this definition")

Custom magic method to unwrap inner value from container.

Should be redefined for ones that actually have values.

And for ones that raise an exception for no values.

Note

As a part of the contract, failed `unwrap` calls

must raise [`returns.primitives.exceptions.UnwrapFailedError`](index.html#returns.primitives.exceptions.UnwrapFailedError "returns.primitives.exceptions.UnwrapFailedError")

exception.

This method is the opposite of `failure()`.

Parameters:

**self** (`TypeVar`(`\_UnwrappableType`, bound= Unwrappable)) – 

Return type:

`TypeVar`(`\_FirstType`)

*abstract* failure()[[source]](_modules/returns/interfaces/unwrappable.html#Unwrappable.failure)[¶](#returns.interfaces.unwrappable.Unwrappable.failure "Permalink to this definition")

Custom magic method to unwrap inner value from the failed container.

Note

As a part of the contract, failed `failure` calls

must raise [`returns.primitives.exceptions.UnwrapFailedError`](index.html#returns.primitives.exceptions.UnwrapFailedError "returns.primitives.exceptions.UnwrapFailedError")

exception.

This method is the opposite of `unwrap()`.

Parameters:

**self** (`TypeVar`(`\_UnwrappableType`, bound= Unwrappable)) – 

Return type:

`TypeVar`(`\_SecondType`)

#### Container[¶](#id8 "Permalink to this heading")

 classDiagram

 ApplicativeN <|-- ContainerN

 BindableN <|-- ContainerN

 LawSpecDef <|-- \_LawSpec

 Lawful <|-- ContainerN

 

*final class* \_LawSpec[[source]](_modules/returns/interfaces/container.html#_LawSpec)[¶](#returns.interfaces.container._LawSpec "Permalink to this definition")

Bases: [`LawSpecDef`](index.html#returns.primitives.laws.LawSpecDef "returns.primitives.laws.LawSpecDef")

Container laws.

Definition: <https://wiki.haskell.org/Monad_laws>

Good explanation: <https://bit.ly/2Qsi5re>

*static* left\_identity\_law(*raw\_value*, *container*, *function*)[[source]](_modules/returns/interfaces/container.html#_LawSpec.left_identity_law)[¶](#returns.interfaces.container._LawSpec.left_identity_law "Permalink to this definition")

Left identity.

The first law states that if we take a value, put it in a default

context with return and then feed it to a function by using `bind`,

it’s the same as just taking the value and applying the function to it.

Parameters:

* **raw\_value** (`TypeVar`(`\_FirstType`)) –

* **container** ([`ContainerN`](#returns.interfaces.container.ContainerN "returns.interfaces.container.ContainerN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`ContainerN`](#returns.interfaces.container.ContainerN "returns.interfaces.container.ContainerN"), `TypeVar`(`\_NewType1`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]) –

Return type:

`None`

*static* right\_identity\_law(*container*)[[source]](_modules/returns/interfaces/container.html#_LawSpec.right_identity_law)[¶](#returns.interfaces.container._LawSpec.right_identity_law "Permalink to this definition")

Right identity.

The second law states that if we have a container value

and we use `bind` to feed it to `.from\_value`,

the result is our original container value.

Parameters:

**container** ([`ContainerN`](#returns.interfaces.container.ContainerN "returns.interfaces.container.ContainerN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) – 

Return type:

`None`

*static* associative\_law(*container*, *first*, *second*)[[source]](_modules/returns/interfaces/container.html#_LawSpec.associative_law)[¶](#returns.interfaces.container._LawSpec.associative_law "Permalink to this definition")

Associativity law.

The final monad law says that when

we have a chain of container functions applications with `bind`,

it shouldn’t matter how they’re nested.

Parameters:

* **container** ([`ContainerN`](#returns.interfaces.container.ContainerN "returns.interfaces.container.ContainerN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) –

* **first** (`Callable`[[`TypeVar`(`\_FirstType`)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`ContainerN`](#returns.interfaces.container.ContainerN "returns.interfaces.container.ContainerN"), `TypeVar`(`\_NewType1`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]) –

* **second** (`Callable`[[`TypeVar`(`\_NewType1`)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`ContainerN`](#returns.interfaces.container.ContainerN "returns.interfaces.container.ContainerN"), `TypeVar`(`\_NewType2`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]) –

Return type:

`None`

*class* ContainerN[[source]](_modules/returns/interfaces/container.html#ContainerN)[¶](#returns.interfaces.container.ContainerN "Permalink to this definition")

Bases: [`ApplicativeN`](#returns.interfaces.applicative.ApplicativeN "returns.interfaces.applicative.ApplicativeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`], [`BindableN`](#returns.interfaces.bindable.BindableN "returns.interfaces.bindable.BindableN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`], [`Lawful`](index.html#returns.primitives.laws.Lawful "returns.primitives.laws.Lawful")[`ContainerN[\_FirstType, \_SecondType, \_ThirdType]`]

Handy alias for types with `.bind`, `.map`, and `.apply` methods.

Should be a base class for almost any containers you write.

See also

* <https://bit.ly/2CTEVov>

\_laws*: `ClassVar`[`Sequence`[[`Law`](index.html#returns.primitives.laws.Law "returns.primitives.laws.Law")]]* *= (<returns.primitives.laws.Law3 object>, <returns.primitives.laws.Law1 object>, <returns.primitives.laws.Law3 object>)*[¶](#returns.interfaces.container.ContainerN._laws "Permalink to this definition")

Some classes and interfaces might have laws, some might not have any.

Container1[¶](#returns.interfaces.container.Container1 "Permalink to this definition")

Type alias for kinds with one type argument.

alias of [`ContainerN`](#returns.interfaces.container.ContainerN "returns.interfaces.container.ContainerN")[`\_FirstType`, `NoReturn`, `NoReturn`]

Container2[¶](#returns.interfaces.container.Container2 "Permalink to this definition")

Type alias for kinds with two type arguments.

alias of [`ContainerN`](#returns.interfaces.container.ContainerN "returns.interfaces.container.ContainerN")[`\_FirstType`, `\_SecondType`, `NoReturn`]

Container3[¶](#returns.interfaces.container.Container3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`ContainerN`](#returns.interfaces.container.ContainerN "returns.interfaces.container.ContainerN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

#### Failable[¶](#failable "Permalink to this heading")

 classDiagram

 ContainerN <|-- FailableN

 FailableN <|-- DiverseFailableN

 FailableN <|-- SingleFailableN

 LashableN <|-- FailableN

 LawSpecDef <|-- \_DiverseFailableLawSpec

 LawSpecDef <|-- \_FailableLawSpec

 LawSpecDef <|-- \_SingleFailableLawSpec

 Lawful <|-- DiverseFailableN

 Lawful <|-- FailableN

 SwappableN <|-- DiverseFailableN

 

*final class* \_FailableLawSpec[[source]](_modules/returns/interfaces/failable.html#_FailableLawSpec)[¶](#returns.interfaces.failable._FailableLawSpec "Permalink to this definition")

Bases: [`LawSpecDef`](index.html#returns.primitives.laws.LawSpecDef "returns.primitives.laws.LawSpecDef")

Failable laws.

We need to be sure that `.lash` won’t lash success types.

*static* lash\_short\_circuit\_law(*raw\_value*, *container*, *function*)[[source]](_modules/returns/interfaces/failable.html#_FailableLawSpec.lash_short_circuit_law)[¶](#returns.interfaces.failable._FailableLawSpec.lash_short_circuit_law "Permalink to this definition")

Ensures that you cannot lash a success.

Parameters:

* **raw\_value** (`TypeVar`(`\_FirstType`)) –

* **container** ([`FailableN`](#returns.interfaces.failable.FailableN "returns.interfaces.failable.FailableN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) –

* **function** (`Callable`[[`TypeVar`(`\_SecondType`)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`FailableN`](#returns.interfaces.failable.FailableN "returns.interfaces.failable.FailableN"), `TypeVar`(`\_FirstType`), `TypeVar`(`\_NewFirstType`), `TypeVar`(`\_ThirdType`)]]) –

Return type:

`None`

*class* FailableN[[source]](_modules/returns/interfaces/failable.html#FailableN)[¶](#returns.interfaces.failable.FailableN "Permalink to this definition")

Bases: [`ContainerN`](#returns.interfaces.container.ContainerN "returns.interfaces.container.ContainerN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`], [`LashableN`](#returns.interfaces.lashable.LashableN "returns.interfaces.lashable.LashableN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`], [`Lawful`](index.html#returns.primitives.laws.Lawful "returns.primitives.laws.Lawful")[`FailableN[\_FirstType, \_SecondType, \_ThirdType]`]

Base type for types that can fail.

It is a raw type and should not be used directly.

Use `SingleFailableN` and `DiverseFailableN` instead.

\_laws*: `ClassVar`[`Sequence`[[`Law`](index.html#returns.primitives.laws.Law "returns.primitives.laws.Law")]]* *= (<returns.primitives.laws.Law3 object>,)*[¶](#returns.interfaces.failable.FailableN._laws "Permalink to this definition")

Some classes and interfaces might have laws, some might not have any.

Failable2[¶](#returns.interfaces.failable.Failable2 "Permalink to this definition")

Type alias for kinds with two type arguments.

alias of [`FailableN`](#returns.interfaces.failable.FailableN "returns.interfaces.failable.FailableN")[`\_FirstType`, `\_SecondType`, `NoReturn`]

Failable3[¶](#returns.interfaces.failable.Failable3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`FailableN`](#returns.interfaces.failable.FailableN "returns.interfaces.failable.FailableN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

*final class* \_SingleFailableLawSpec[[source]](_modules/returns/interfaces/failable.html#_SingleFailableLawSpec)[¶](#returns.interfaces.failable._SingleFailableLawSpec "Permalink to this definition")

Bases: [`LawSpecDef`](index.html#returns.primitives.laws.LawSpecDef "returns.primitives.laws.LawSpecDef")

Single Failable laws.

We need to be sure that `.map` and `.bind`

works correctly for `empty` property.

*static* map\_short\_circuit\_law(*container*, *function*)[[source]](_modules/returns/interfaces/failable.html#_SingleFailableLawSpec.map_short_circuit_law)[¶](#returns.interfaces.failable._SingleFailableLawSpec.map_short_circuit_law "Permalink to this definition")

Ensures that you cannot map from the empty property.

Parameters:

* **container** ([`SingleFailableN`](#returns.interfaces.failable.SingleFailableN "returns.interfaces.failable.SingleFailableN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], `TypeVar`(`\_NewFirstType`)]) –

Return type:

`None`

*static* bind\_short\_circuit\_law(*container*, *function*)[[source]](_modules/returns/interfaces/failable.html#_SingleFailableLawSpec.bind_short_circuit_law)[¶](#returns.interfaces.failable._SingleFailableLawSpec.bind_short_circuit_law "Permalink to this definition")

Ensures that you cannot bind from the empty property.

Parameters:

* **container** ([`SingleFailableN`](#returns.interfaces.failable.SingleFailableN "returns.interfaces.failable.SingleFailableN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`SingleFailableN`](#returns.interfaces.failable.SingleFailableN "returns.interfaces.failable.SingleFailableN"), `TypeVar`(`\_NewFirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]) –

Return type:

`None`

*static* apply\_short\_circuit\_law(*container*, *function*)[[source]](_modules/returns/interfaces/failable.html#_SingleFailableLawSpec.apply_short_circuit_law)[¶](#returns.interfaces.failable._SingleFailableLawSpec.apply_short_circuit_law "Permalink to this definition")

Ensures that you cannot apply from the empty property.

Parameters:

* **container** ([`SingleFailableN`](#returns.interfaces.failable.SingleFailableN "returns.interfaces.failable.SingleFailableN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], `TypeVar`(`\_NewFirstType`)]) –

Return type:

`None`

*class* SingleFailableN[[source]](_modules/returns/interfaces/failable.html#SingleFailableN)[¶](#returns.interfaces.failable.SingleFailableN "Permalink to this definition")

Bases: [`FailableN`](#returns.interfaces.failable.FailableN "returns.interfaces.failable.FailableN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

Base type for types that have just only one failed value.

Like `Maybe` types where the only failed value is `Nothing`.

\_laws*: `ClassVar`[`Sequence`[[`Law`](index.html#returns.primitives.laws.Law "returns.primitives.laws.Law")]]* *= (<returns.primitives.laws.Law2 object>, <returns.primitives.laws.Law2 object>, <returns.primitives.laws.Law2 object>)*[¶](#returns.interfaces.failable.SingleFailableN._laws "Permalink to this definition")

Some classes and interfaces might have laws, some might not have any.

*abstract property* empty*: [SingleFailableN](index.html#returns.interfaces.failable.SingleFailableN "returns.interfaces.failable.SingleFailableN")[\_FirstType, \_SecondType, \_ThirdType]*[¶](#returns.interfaces.failable.SingleFailableN.empty "Permalink to this definition")

This property represents the failed value.

:param self:

:type self: `TypeVar`(`\_SingleFailableType`, bound= SingleFailableN)

SingleFailable2[¶](#returns.interfaces.failable.SingleFailable2 "Permalink to this definition")

Type alias for kinds with two types arguments.

alias of [`SingleFailableN`](#returns.interfaces.failable.SingleFailableN "returns.interfaces.failable.SingleFailableN")[`\_FirstType`, `\_SecondType`, `NoReturn`]

SingleFailable3[¶](#returns.interfaces.failable.SingleFailable3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`SingleFailableN`](#returns.interfaces.failable.SingleFailableN "returns.interfaces.failable.SingleFailableN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

*final class* \_DiverseFailableLawSpec[[source]](_modules/returns/interfaces/failable.html#_DiverseFailableLawSpec)[¶](#returns.interfaces.failable._DiverseFailableLawSpec "Permalink to this definition")

Bases: [`LawSpecDef`](index.html#returns.primitives.laws.LawSpecDef "returns.primitives.laws.LawSpecDef")

Diverse Failable laws.

We need to be sure that `.map`, `.bind`, `.apply` and `.alt`

works correctly for both success and failure types.

*static* map\_short\_circuit\_law(*raw\_value*, *container*, *function*)[[source]](_modules/returns/interfaces/failable.html#_DiverseFailableLawSpec.map_short_circuit_law)[¶](#returns.interfaces.failable._DiverseFailableLawSpec.map_short_circuit_law "Permalink to this definition")

Ensures that you cannot map a failure.

Parameters:

* **raw\_value** (`TypeVar`(`\_SecondType`)) –

* **container** ([`DiverseFailableN`](#returns.interfaces.failable.DiverseFailableN "returns.interfaces.failable.DiverseFailableN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], `TypeVar`(`\_NewFirstType`)]) –

Return type:

`None`

*static* bind\_short\_circuit\_law(*raw\_value*, *container*, *function*)[[source]](_modules/returns/interfaces/failable.html#_DiverseFailableLawSpec.bind_short_circuit_law)[¶](#returns.interfaces.failable._DiverseFailableLawSpec.bind_short_circuit_law "Permalink to this definition")

Ensures that you cannot bind a failure.

See: <https://wiki.haskell.org/Typeclassopedia#MonadFail>

Parameters:

* **raw\_value** (`TypeVar`(`\_SecondType`)) –

* **container** ([`DiverseFailableN`](#returns.interfaces.failable.DiverseFailableN "returns.interfaces.failable.DiverseFailableN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`DiverseFailableN`](#returns.interfaces.failable.DiverseFailableN "returns.interfaces.failable.DiverseFailableN"), `TypeVar`(`\_NewFirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]) –

Return type:

`None`

*static* apply\_short\_circuit\_law(*raw\_value*, *container*, *function*)[[source]](_modules/returns/interfaces/failable.html#_DiverseFailableLawSpec.apply_short_circuit_law)[¶](#returns.interfaces.failable._DiverseFailableLawSpec.apply_short_circuit_law "Permalink to this definition")

Ensures that you cannot apply a failure.

Parameters:

* **raw\_value** (`TypeVar`(`\_SecondType`)) –

* **container** ([`DiverseFailableN`](#returns.interfaces.failable.DiverseFailableN "returns.interfaces.failable.DiverseFailableN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], `TypeVar`(`\_NewFirstType`)]) –

Return type:

`None`

*static* alt\_short\_circuit\_law(*raw\_value*, *container*, *function*)[[source]](_modules/returns/interfaces/failable.html#_DiverseFailableLawSpec.alt_short_circuit_law)[¶](#returns.interfaces.failable._DiverseFailableLawSpec.alt_short_circuit_law "Permalink to this definition")

Ensures that you cannot alt a success.

Parameters:

* **raw\_value** (`TypeVar`(`\_SecondType`)) –

* **container** ([`DiverseFailableN`](#returns.interfaces.failable.DiverseFailableN "returns.interfaces.failable.DiverseFailableN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) –

* **function** (`Callable`[[`TypeVar`(`\_SecondType`)], `TypeVar`(`\_NewFirstType`)]) –

Return type:

`None`

*class* DiverseFailableN[[source]](_modules/returns/interfaces/failable.html#DiverseFailableN)[¶](#returns.interfaces.failable.DiverseFailableN "Permalink to this definition")

Bases: [`FailableN`](#returns.interfaces.failable.FailableN "returns.interfaces.failable.FailableN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`], [`SwappableN`](#returns.interfaces.swappable.SwappableN "returns.interfaces.swappable.SwappableN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`], [`Lawful`](index.html#returns.primitives.laws.Lawful "returns.primitives.laws.Lawful")[`DiverseFailableN[\_FirstType, \_SecondType, \_ThirdType]`]

Base type for types that have any failed value.

Like `Result` types.

\_laws*: `ClassVar`[`Sequence`[[`Law`](index.html#returns.primitives.laws.Law "returns.primitives.laws.Law")]]* *= (<returns.primitives.laws.Law3 object>, <returns.primitives.laws.Law3 object>, <returns.primitives.laws.Law3 object>, <returns.primitives.laws.Law3 object>)*[¶](#returns.interfaces.failable.DiverseFailableN._laws "Permalink to this definition")

Some classes and interfaces might have laws, some might not have any.

*abstract classmethod* from\_failure(*inner\_value*)[[source]](_modules/returns/interfaces/failable.html#DiverseFailableN.from_failure)[¶](#returns.interfaces.failable.DiverseFailableN.from_failure "Permalink to this definition")

Unit method to create new containers from any raw value.

Parameters:

**inner\_value** (`TypeVar`(`\_UpdatedType`)) – 

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_DiverseFailableType`, bound= DiverseFailableN), `TypeVar`(`\_FirstType`), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_ThirdType`)]

DiverseFailable2[¶](#returns.interfaces.failable.DiverseFailable2 "Permalink to this definition")

Type alias for kinds with two type arguments.

alias of [`DiverseFailableN`](#returns.interfaces.failable.DiverseFailableN "returns.interfaces.failable.DiverseFailableN")[`\_FirstType`, `\_SecondType`, `NoReturn`]

DiverseFailable3[¶](#returns.interfaces.failable.DiverseFailable3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`DiverseFailableN`](#returns.interfaces.failable.DiverseFailableN "returns.interfaces.failable.DiverseFailableN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

#### Maybe specific[¶](#maybe-specific "Permalink to this heading")

 classDiagram

 Equable <|-- MaybeBasedN

 LawSpecDef <|-- \_LawSpec

 Lawful <|-- MaybeLikeN

 MaybeLikeN <|-- MaybeBasedN

 SingleFailableN <|-- MaybeLikeN

 Unwrappable <|-- MaybeBasedN

 

*final class* \_LawSpec[[source]](_modules/returns/interfaces/specific/maybe.html#_LawSpec)[¶](#returns.interfaces.specific.maybe._LawSpec "Permalink to this definition")

Bases: [`LawSpecDef`](index.html#returns.primitives.laws.LawSpecDef "returns.primitives.laws.LawSpecDef")

Maybe laws.

We need to be sure that

`.map`, `.bind`, `.bind\_optional`, and `.lash`

works correctly for both successful and failed types.

*static* map\_short\_circuit\_law(*container*, *function*)[[source]](_modules/returns/interfaces/specific/maybe.html#_LawSpec.map_short_circuit_law)[¶](#returns.interfaces.specific.maybe._LawSpec.map_short_circuit_law "Permalink to this definition")

Ensures that you cannot map from failures.

Parameters:

* **container** ([`MaybeLikeN`](#returns.interfaces.specific.maybe.MaybeLikeN "returns.interfaces.specific.maybe.MaybeLikeN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], `TypeVar`(`\_NewType1`)]) –

Return type:

`None`

*static* bind\_short\_circuit\_law(*container*, *function*)[[source]](_modules/returns/interfaces/specific/maybe.html#_LawSpec.bind_short_circuit_law)[¶](#returns.interfaces.specific.maybe._LawSpec.bind_short_circuit_law "Permalink to this definition")

Ensures that you cannot bind from failures.

Parameters:

* **container** ([`MaybeLikeN`](#returns.interfaces.specific.maybe.MaybeLikeN "returns.interfaces.specific.maybe.MaybeLikeN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`MaybeLikeN`](#returns.interfaces.specific.maybe.MaybeLikeN "returns.interfaces.specific.maybe.MaybeLikeN"), `TypeVar`(`\_NewType1`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]) –

Return type:

`None`

*static* bind\_optional\_short\_circuit\_law(*container*, *function*)[[source]](_modules/returns/interfaces/specific/maybe.html#_LawSpec.bind_optional_short_circuit_law)[¶](#returns.interfaces.specific.maybe._LawSpec.bind_optional_short_circuit_law "Permalink to this definition")

Ensures that you cannot bind from failures.

Parameters:

* **container** ([`MaybeLikeN`](#returns.interfaces.specific.maybe.MaybeLikeN "returns.interfaces.specific.maybe.MaybeLikeN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], `Optional`[`TypeVar`(`\_NewType1`)]]) –

Return type:

`None`

*static* lash\_short\_circuit\_law(*raw\_value*, *container*, *function*)[[source]](_modules/returns/interfaces/specific/maybe.html#_LawSpec.lash_short_circuit_law)[¶](#returns.interfaces.specific.maybe._LawSpec.lash_short_circuit_law "Permalink to this definition")

Ensures that you cannot lash a success.

Parameters:

* **raw\_value** (`TypeVar`(`\_FirstType`)) –

* **container** ([`MaybeLikeN`](#returns.interfaces.specific.maybe.MaybeLikeN "returns.interfaces.specific.maybe.MaybeLikeN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) –

* **function** (`Callable`[[`TypeVar`(`\_SecondType`)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`MaybeLikeN`](#returns.interfaces.specific.maybe.MaybeLikeN "returns.interfaces.specific.maybe.MaybeLikeN"), `TypeVar`(`\_FirstType`), `TypeVar`(`\_NewType1`), `TypeVar`(`\_ThirdType`)]]) –

Return type:

`None`

*static* unit\_structure\_law(*container*, *function*)[[source]](_modules/returns/interfaces/specific/maybe.html#_LawSpec.unit_structure_law)[¶](#returns.interfaces.specific.maybe._LawSpec.unit_structure_law "Permalink to this definition")

Ensures `None` is treated specially.

Parameters:

* **container** ([`MaybeLikeN`](#returns.interfaces.specific.maybe.MaybeLikeN "returns.interfaces.specific.maybe.MaybeLikeN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], `None`]) –

Return type:

`None`

*class* MaybeLikeN[[source]](_modules/returns/interfaces/specific/maybe.html#MaybeLikeN)[¶](#returns.interfaces.specific.maybe.MaybeLikeN "Permalink to this definition")

Bases: [`SingleFailableN`](#returns.interfaces.failable.SingleFailableN "returns.interfaces.failable.SingleFailableN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`], [`Lawful`](index.html#returns.primitives.laws.Lawful "returns.primitives.laws.Lawful")[`MaybeLikeN[\_FirstType, \_SecondType, \_ThirdType]`]

Type for values that do look like a `Maybe`.

For example, `RequiresContextMaybe` should be created from this interface.

Cannot be unwrapped or compared.

\_laws*: `ClassVar`[`Sequence`[[`Law`](index.html#returns.primitives.laws.Law "returns.primitives.laws.Law")]]* *= (<returns.primitives.laws.Law2 object>, <returns.primitives.laws.Law2 object>, <returns.primitives.laws.Law2 object>, <returns.primitives.laws.Law3 object>, <returns.primitives.laws.Law2 object>)*[¶](#returns.interfaces.specific.maybe.MaybeLikeN._laws "Permalink to this definition")

Some classes and interfaces might have laws, some might not have any.

*abstract* bind\_optional(*function*)[[source]](_modules/returns/interfaces/specific/maybe.html#MaybeLikeN.bind_optional)[¶](#returns.interfaces.specific.maybe.MaybeLikeN.bind_optional "Permalink to this definition")

Binds a function that returns `Optional` values.

Parameters:

* **self** (`TypeVar`(`\_MaybeLikeType`, bound= MaybeLikeN)) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], `Optional`[`TypeVar`(`\_UpdatedType`)]]) –

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_MaybeLikeType`, bound= MaybeLikeN), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

*abstract classmethod* from\_optional(*inner\_value*)[[source]](_modules/returns/interfaces/specific/maybe.html#MaybeLikeN.from_optional)[¶](#returns.interfaces.specific.maybe.MaybeLikeN.from_optional "Permalink to this definition")

Unit method to create containers from `Optional` value.

Parameters:

**inner\_value** (`Optional`[`TypeVar`(`\_ValueType`)]) – 

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_MaybeLikeType`, bound= MaybeLikeN), `TypeVar`(`\_ValueType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

MaybeLike2[¶](#returns.interfaces.specific.maybe.MaybeLike2 "Permalink to this definition")

Type alias for kinds with two type arguments.

alias of [`MaybeLikeN`](#returns.interfaces.specific.maybe.MaybeLikeN "returns.interfaces.specific.maybe.MaybeLikeN")[`\_FirstType`, `\_SecondType`, `NoReturn`]

MaybeLike3[¶](#returns.interfaces.specific.maybe.MaybeLike3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`MaybeLikeN`](#returns.interfaces.specific.maybe.MaybeLikeN "returns.interfaces.specific.maybe.MaybeLikeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

*class* MaybeBasedN[[source]](_modules/returns/interfaces/specific/maybe.html#MaybeBasedN)[¶](#returns.interfaces.specific.maybe.MaybeBasedN "Permalink to this definition")

Bases: [`MaybeLikeN`](#returns.interfaces.specific.maybe.MaybeLikeN "returns.interfaces.specific.maybe.MaybeLikeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`], [`Unwrappable`](#returns.interfaces.unwrappable.Unwrappable "returns.interfaces.unwrappable.Unwrappable")[`\_FirstType`, `None`], [`Equable`](#returns.interfaces.equable.Equable "returns.interfaces.equable.Equable")

Concrete interface for `Maybe` type.

Can be unwrapped and compared.

*abstract* or\_else\_call(*function*)[[source]](_modules/returns/interfaces/specific/maybe.html#MaybeBasedN.or_else_call)[¶](#returns.interfaces.specific.maybe.MaybeBasedN.or_else_call "Permalink to this definition")

Calls a function in case there nothing to unwrap.

Parameters:

**function** (`Callable`[[], `TypeVar`(`\_ValueType`)]) – 

Return type:

`Union`[`TypeVar`(`\_FirstType`), `TypeVar`(`\_ValueType`)]

MaybeBased2[¶](#returns.interfaces.specific.maybe.MaybeBased2 "Permalink to this definition")

Type alias for kinds with two type arguments.

alias of [`MaybeBasedN`](#returns.interfaces.specific.maybe.MaybeBasedN "returns.interfaces.specific.maybe.MaybeBasedN")[`\_FirstType`, `\_SecondType`, `NoReturn`]

MaybeBased3[¶](#returns.interfaces.specific.maybe.MaybeBased3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`MaybeBasedN`](#returns.interfaces.specific.maybe.MaybeBasedN "returns.interfaces.specific.maybe.MaybeBasedN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

#### Result specific[¶](#result-specific "Permalink to this heading")

 classDiagram

 DiverseFailableN <|-- ResultLikeN

 Equable <|-- UnwrappableResult

 ResultLikeN <|-- UnwrappableResult

 Unwrappable <|-- UnwrappableResult

 UnwrappableResult <|-- ResultBasedN

 An interface that represents a pure computation result.

For impure result see

[`returns.interfaces.specific.ioresult.IOResultLikeN`](#returns.interfaces.specific.ioresult.IOResultLikeN "returns.interfaces.specific.ioresult.IOResultLikeN") type.

*class* ResultLikeN[[source]](_modules/returns/interfaces/specific/result.html#ResultLikeN)[¶](#returns.interfaces.specific.result.ResultLikeN "Permalink to this definition")

Bases: [`DiverseFailableN`](#returns.interfaces.failable.DiverseFailableN "returns.interfaces.failable.DiverseFailableN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

Base types for types that looks like `Result` but cannot be unwrapped.

Like `RequiresContextResult` or `FutureResult`.

*abstract* bind\_result(*function*)[[source]](_modules/returns/interfaces/specific/result.html#ResultLikeN.bind_result)[¶](#returns.interfaces.specific.result.ResultLikeN.bind_result "Permalink to this definition")

Runs `Result` returning function over a container.

Parameters:

* **self** (`TypeVar`(`\_ResultLikeType`, bound= ResultLikeN)) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], [`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`)]]) –

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ResultLikeType`, bound= ResultLikeN), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

*abstract classmethod* from\_result(*inner\_value*)[[source]](_modules/returns/interfaces/specific/result.html#ResultLikeN.from_result)[¶](#returns.interfaces.specific.result.ResultLikeN.from_result "Permalink to this definition")

Unit method to create new containers from any raw value.

Parameters:

**inner\_value** ([`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_ValueType`), `TypeVar`(`\_ErrorType`)]) – 

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ResultLikeType`, bound= ResultLikeN), `TypeVar`(`\_ValueType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_ThirdType`)]

ResultLike2[¶](#returns.interfaces.specific.result.ResultLike2 "Permalink to this definition")

Type alias for kinds with two type arguments.

alias of [`ResultLikeN`](#returns.interfaces.specific.result.ResultLikeN "returns.interfaces.specific.result.ResultLikeN")[`\_FirstType`, `\_SecondType`, `NoReturn`]

ResultLike3[¶](#returns.interfaces.specific.result.ResultLike3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`ResultLikeN`](#returns.interfaces.specific.result.ResultLikeN "returns.interfaces.specific.result.ResultLikeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

*class* UnwrappableResult[[source]](_modules/returns/interfaces/specific/result.html#UnwrappableResult)[¶](#returns.interfaces.specific.result.UnwrappableResult "Permalink to this definition")

Bases: [`ResultLikeN`](#returns.interfaces.specific.result.ResultLikeN "returns.interfaces.specific.result.ResultLikeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`], [`Unwrappable`](#returns.interfaces.unwrappable.Unwrappable "returns.interfaces.unwrappable.Unwrappable")[`\_FirstUnwrappableType`, `\_SecondUnwrappableType`], [`Equable`](#returns.interfaces.equable.Equable "returns.interfaces.equable.Equable")

Intermediate type with 5 type arguments that represents unwrappable result.

It is a raw type and should not be used directly.

Use `ResultBasedN` and `IOResultBasedN` instead.

*class* ResultBasedN[[source]](_modules/returns/interfaces/specific/result.html#ResultBasedN)[¶](#returns.interfaces.specific.result.ResultBasedN "Permalink to this definition")

Bases: [`UnwrappableResult`](#returns.interfaces.specific.result.UnwrappableResult "returns.interfaces.specific.result.UnwrappableResult")[`\_FirstType`, `\_SecondType`, `\_ThirdType`, `\_FirstType`, `\_SecondType`]

Base type for real `Result` types.

Can be unwrapped.

ResultBased2[¶](#returns.interfaces.specific.result.ResultBased2 "Permalink to this definition")

Type alias for kinds with two type arguments.

alias of [`ResultBasedN`](#returns.interfaces.specific.result.ResultBasedN "returns.interfaces.specific.result.ResultBasedN")[`\_FirstType`, `\_SecondType`, `NoReturn`]

ResultBased3[¶](#returns.interfaces.specific.result.ResultBased3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`ResultBasedN`](#returns.interfaces.specific.result.ResultBasedN "returns.interfaces.specific.result.ResultBasedN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

#### IO specific[¶](#io-specific "Permalink to this heading")

 classDiagram

 ContainerN <|-- IOLikeN

 Equable <|-- IOBasedN

 IOLikeN <|-- IOBasedN

 

*class* IOLikeN[[source]](_modules/returns/interfaces/specific/io.html#IOLikeN)[¶](#returns.interfaces.specific.io.IOLikeN "Permalink to this definition")

Bases: [`ContainerN`](#returns.interfaces.container.ContainerN "returns.interfaces.container.ContainerN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

Represents interface for types that looks like fearless `IO`.

This type means that `IO` cannot fail. Like random numbers, date, etc.

Don’t use this type for `IO` that can. Instead, use

[`returns.interfaces.specific.ioresult.IOResultBasedN`](#returns.interfaces.specific.ioresult.IOResultBasedN "returns.interfaces.specific.ioresult.IOResultBasedN") type.

*abstract* bind\_io(*function*)[[source]](_modules/returns/interfaces/specific/io.html#IOLikeN.bind_io)[¶](#returns.interfaces.specific.io.IOLikeN.bind_io "Permalink to this definition")

Allows to apply a wrapped function over a container.

Parameters:

* **self** (`TypeVar`(`\_IOLikeType`, bound= IOLikeN)) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], [`IO`](index.html#returns.io.IO "returns.io.IO")[`TypeVar`(`\_UpdatedType`)]]) –

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_IOLikeType`, bound= IOLikeN), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

*abstract classmethod* from\_io(*inner\_value*)[[source]](_modules/returns/interfaces/specific/io.html#IOLikeN.from_io)[¶](#returns.interfaces.specific.io.IOLikeN.from_io "Permalink to this definition")

Unit method to create new containers from successful `IO`.

Parameters:

**inner\_value** ([`IO`](index.html#returns.io.IO "returns.io.IO")[`TypeVar`(`\_UpdatedType`)]) – 

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_IOLikeType`, bound= IOLikeN), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

IOLike1[¶](#returns.interfaces.specific.io.IOLike1 "Permalink to this definition")

Type alias for kinds with one type argument.

alias of [`IOLikeN`](#returns.interfaces.specific.io.IOLikeN "returns.interfaces.specific.io.IOLikeN")[`\_FirstType`, `NoReturn`, `NoReturn`]

IOLike2[¶](#returns.interfaces.specific.io.IOLike2 "Permalink to this definition")

Type alias for kinds with two type arguments.

alias of [`IOLikeN`](#returns.interfaces.specific.io.IOLikeN "returns.interfaces.specific.io.IOLikeN")[`\_FirstType`, `\_SecondType`, `NoReturn`]

IOLike3[¶](#returns.interfaces.specific.io.IOLike3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`IOLikeN`](#returns.interfaces.specific.io.IOLikeN "returns.interfaces.specific.io.IOLikeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

*class* IOBasedN[[source]](_modules/returns/interfaces/specific/io.html#IOBasedN)[¶](#returns.interfaces.specific.io.IOBasedN "Permalink to this definition")

Bases: [`IOLikeN`](#returns.interfaces.specific.io.IOLikeN "returns.interfaces.specific.io.IOLikeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`], [`Equable`](#returns.interfaces.equable.Equable "returns.interfaces.equable.Equable")

Represents the base interface for types that do fearless `IO`.

This type means that `IO` cannot fail. Like random numbers, date, etc.

Don’t use this type for `IO` that can. Instead, use

[`returns.interfaces.specific.ioresult.IOResultBasedN`](#returns.interfaces.specific.ioresult.IOResultBasedN "returns.interfaces.specific.ioresult.IOResultBasedN") type.

This interface also supports direct comparison of two values.

While `IOLikeN` is different. It can be lazy and cannot be compared.

IOBased1[¶](#returns.interfaces.specific.io.IOBased1 "Permalink to this definition")

Type alias for kinds with one type argument.

alias of [`IOBasedN`](#returns.interfaces.specific.io.IOBasedN "returns.interfaces.specific.io.IOBasedN")[`\_FirstType`, `NoReturn`, `NoReturn`]

IOBased2[¶](#returns.interfaces.specific.io.IOBased2 "Permalink to this definition")

Type alias for kinds with two type arguments.

alias of [`IOBasedN`](#returns.interfaces.specific.io.IOBasedN "returns.interfaces.specific.io.IOBasedN")[`\_FirstType`, `\_SecondType`, `NoReturn`]

IOBased3[¶](#returns.interfaces.specific.io.IOBased3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`IOBasedN`](#returns.interfaces.specific.io.IOBasedN "returns.interfaces.specific.io.IOBasedN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

#### IOResult specific[¶](#ioresult-specific "Permalink to this heading")

 classDiagram

 IOBasedN <|-- IOResultBasedN

 IOLikeN <|-- IOResultLikeN

 IOResultLikeN <|-- IOResultBasedN

 ResultLikeN <|-- IOResultLikeN

 UnwrappableResult <|-- IOResultBasedN

 An interface for types that do `IO` and can fail.

It is a base interface for both sync and async `IO` stacks.

*class* IOResultLikeN[[source]](_modules/returns/interfaces/specific/ioresult.html#IOResultLikeN)[¶](#returns.interfaces.specific.ioresult.IOResultLikeN "Permalink to this definition")

Bases: [`IOLikeN`](#returns.interfaces.specific.io.IOLikeN "returns.interfaces.specific.io.IOLikeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`], [`ResultLikeN`](#returns.interfaces.specific.result.ResultLikeN "returns.interfaces.specific.result.ResultLikeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

Base type for types that look like `IOResult` but cannot be unwrapped.

Like `FutureResult` or `RequiresContextIOResult`.

*abstract* bind\_ioresult(*function*)[[source]](_modules/returns/interfaces/specific/ioresult.html#IOResultLikeN.bind_ioresult)[¶](#returns.interfaces.specific.ioresult.IOResultLikeN.bind_ioresult "Permalink to this definition")

Runs `IOResult` returning function over a container.

Parameters:

* **self** (`TypeVar`(`\_IOResultLikeType`, bound= IOResultLikeN)) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], [`IOResult`](index.html#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`)]]) –

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_IOResultLikeType`, bound= IOResultLikeN), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

*abstract* compose\_result(*function*)[[source]](_modules/returns/interfaces/specific/ioresult.html#IOResultLikeN.compose_result)[¶](#returns.interfaces.specific.ioresult.IOResultLikeN.compose_result "Permalink to this definition")

Allows to compose the underlying `Result` with a function.

Parameters:

* **self** (`TypeVar`(`\_IOResultLikeType`, bound= IOResultLikeN)) –

* **function** (`Callable`[[[`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_IOResultLikeType`, bound= IOResultLikeN), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]) –

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_IOResultLikeType`, bound= IOResultLikeN), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

*abstract classmethod* from\_ioresult(*inner\_value*)[[source]](_modules/returns/interfaces/specific/ioresult.html#IOResultLikeN.from_ioresult)[¶](#returns.interfaces.specific.ioresult.IOResultLikeN.from_ioresult "Permalink to this definition")

Unit method to create new containers from `IOResult` type.

Parameters:

**inner\_value** ([`IOResult`](index.html#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_ValueType`), `TypeVar`(`\_ErrorType`)]) – 

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_IOResultLikeType`, bound= IOResultLikeN), `TypeVar`(`\_ValueType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_ThirdType`)]

*abstract classmethod* from\_failed\_io(*inner\_value*)[[source]](_modules/returns/interfaces/specific/ioresult.html#IOResultLikeN.from_failed_io)[¶](#returns.interfaces.specific.ioresult.IOResultLikeN.from_failed_io "Permalink to this definition")

Unit method to create new containers from failed `IO`.

Parameters:

**inner\_value** ([`IO`](index.html#returns.io.IO "returns.io.IO")[`TypeVar`(`\_ErrorType`)]) – 

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_IOResultLikeType`, bound= IOResultLikeN), `TypeVar`(`\_FirstType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_ThirdType`)]

IOResultLike2[¶](#returns.interfaces.specific.ioresult.IOResultLike2 "Permalink to this definition")

Type alias for kinds with two type arguments.

alias of [`IOResultLikeN`](#returns.interfaces.specific.ioresult.IOResultLikeN "returns.interfaces.specific.ioresult.IOResultLikeN")[`\_FirstType`, `\_SecondType`, `NoReturn`]

IOResultLike3[¶](#returns.interfaces.specific.ioresult.IOResultLike3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`IOResultLikeN`](#returns.interfaces.specific.ioresult.IOResultLikeN "returns.interfaces.specific.ioresult.IOResultLikeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

*class* IOResultBasedN[[source]](_modules/returns/interfaces/specific/ioresult.html#IOResultBasedN)[¶](#returns.interfaces.specific.ioresult.IOResultBasedN "Permalink to this definition")

Bases: [`IOResultLikeN`](#returns.interfaces.specific.ioresult.IOResultLikeN "returns.interfaces.specific.ioresult.IOResultLikeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`], [`IOBasedN`](#returns.interfaces.specific.io.IOBasedN "returns.interfaces.specific.io.IOBasedN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`], [`UnwrappableResult`](#returns.interfaces.specific.result.UnwrappableResult "returns.interfaces.specific.result.UnwrappableResult")[`\_FirstType`, `\_SecondType`, `\_ThirdType`, `IO[\_FirstType]`, `IO[\_SecondType]`]

Base type for real `IOResult` types.

Can be unwrapped.

IOResultBased2[¶](#returns.interfaces.specific.ioresult.IOResultBased2 "Permalink to this definition")

Type alias for kinds with two type arguments.

alias of [`IOResultBasedN`](#returns.interfaces.specific.ioresult.IOResultBasedN "returns.interfaces.specific.ioresult.IOResultBasedN")[`\_FirstType`, `\_SecondType`, `NoReturn`]

IOResultBased3[¶](#returns.interfaces.specific.ioresult.IOResultBased3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`IOResultBasedN`](#returns.interfaces.specific.ioresult.IOResultBasedN "returns.interfaces.specific.ioresult.IOResultBasedN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

#### Future specific[¶](#future-specific "Permalink to this heading")

 classDiagram

 AwaitableFutureN <|-- FutureBasedN

 FutureLikeN <|-- FutureBasedN

 Generic <|-- AwaitableFutureN

 IOLikeN <|-- FutureLikeN

 Represents the base interfaces for types that do fearless async operations.

This type means that `Future` cannot fail.

Don’t use this type for async that can. Instead, use

[`returns.interfaces.specific.future\_result.FutureResultBasedN`](#returns.interfaces.specific.future_result.FutureResultBasedN "returns.interfaces.specific.future_result.FutureResultBasedN") type.

*class* FutureLikeN[[source]](_modules/returns/interfaces/specific/future.html#FutureLikeN)[¶](#returns.interfaces.specific.future.FutureLikeN "Permalink to this definition")

Bases: [`IOLikeN`](#returns.interfaces.specific.io.IOLikeN "returns.interfaces.specific.io.IOLikeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

Base type for ones that does look like `Future`.

But at the time this is not a real `Future` and cannot be awaited.

*abstract* bind\_future(*function*)[[source]](_modules/returns/interfaces/specific/future.html#FutureLikeN.bind_future)[¶](#returns.interfaces.specific.future.FutureLikeN.bind_future "Permalink to this definition")

Allows to bind `Future` returning function over a container.

Parameters:

* **self** (`TypeVar`(`\_FutureLikeType`, bound= FutureLikeN)) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], [`Future`](index.html#returns.future.Future "returns.future.Future")[`TypeVar`(`\_UpdatedType`)]]) –

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_FutureLikeType`, bound= FutureLikeN), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

*abstract* bind\_async\_future(*function*)[[source]](_modules/returns/interfaces/specific/future.html#FutureLikeN.bind_async_future)[¶](#returns.interfaces.specific.future.FutureLikeN.bind_async_future "Permalink to this definition")

Allows to bind async `Future` returning function over container.

Parameters:

* **self** (`TypeVar`(`\_FutureLikeType`, bound= FutureLikeN)) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], `Awaitable`[[`Future`](index.html#returns.future.Future "returns.future.Future")[`TypeVar`(`\_UpdatedType`)]]]) –

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_FutureLikeType`, bound= FutureLikeN), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

*abstract* bind\_async(*function*)[[source]](_modules/returns/interfaces/specific/future.html#FutureLikeN.bind_async)[¶](#returns.interfaces.specific.future.FutureLikeN.bind_async "Permalink to this definition")

Binds async function returning the same type of container.

Parameters:

* **self** (`TypeVar`(`\_FutureLikeType`, bound= FutureLikeN)) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], `Awaitable`[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_FutureLikeType`, bound= FutureLikeN), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]]) –

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_FutureLikeType`, bound= FutureLikeN), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

*abstract* bind\_awaitable(*function*)[[source]](_modules/returns/interfaces/specific/future.html#FutureLikeN.bind_awaitable)[¶](#returns.interfaces.specific.future.FutureLikeN.bind_awaitable "Permalink to this definition")

Allows to bind async function over container.

Parameters:

* **self** (`TypeVar`(`\_FutureLikeType`, bound= FutureLikeN)) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], `Awaitable`[`TypeVar`(`\_UpdatedType`)]]) –

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_FutureLikeType`, bound= FutureLikeN), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

*abstract classmethod* from\_future(*inner\_value*)[[source]](_modules/returns/interfaces/specific/future.html#FutureLikeN.from_future)[¶](#returns.interfaces.specific.future.FutureLikeN.from_future "Permalink to this definition")

Unit method to create new containers from successful `Future`.

Parameters:

**inner\_value** ([`Future`](index.html#returns.future.Future "returns.future.Future")[`TypeVar`(`\_UpdatedType`)]) – 

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_FutureLikeType`, bound= FutureLikeN), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

FutureLike1[¶](#returns.interfaces.specific.future.FutureLike1 "Permalink to this definition")

Type alias for kinds with one type argument.

alias of [`FutureLikeN`](#returns.interfaces.specific.future.FutureLikeN "returns.interfaces.specific.future.FutureLikeN")[`\_FirstType`, `NoReturn`, `NoReturn`]

FutureLike2[¶](#returns.interfaces.specific.future.FutureLike2 "Permalink to this definition")

Type alias for kinds with two type arguments.

alias of [`FutureLikeN`](#returns.interfaces.specific.future.FutureLikeN "returns.interfaces.specific.future.FutureLikeN")[`\_FirstType`, `\_SecondType`, `NoReturn`]

FutureLike3[¶](#returns.interfaces.specific.future.FutureLike3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`FutureLikeN`](#returns.interfaces.specific.future.FutureLikeN "returns.interfaces.specific.future.FutureLikeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

*class* AwaitableFutureN[[source]](_modules/returns/interfaces/specific/future.html#AwaitableFutureN)[¶](#returns.interfaces.specific.future.AwaitableFutureN "Permalink to this definition")

Bases: `Generic`[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

Type that provides the required API for `Future` to be async.

Should not be used directly. Use `FutureBasedN` instead.

*abstract async* awaitable()[[source]](_modules/returns/interfaces/specific/future.html#AwaitableFutureN.awaitable)[¶](#returns.interfaces.specific.future.AwaitableFutureN.awaitable "Permalink to this definition")

Underling logic under `await` expression.

Parameters:

**self** (`TypeVar`(`\_AsyncFutureType`, bound= AwaitableFutureN)) – 

Return type:

[`IOLikeN`](#returns.interfaces.specific.io.IOLikeN "returns.interfaces.specific.io.IOLikeN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

AsyncFuture1[¶](#returns.interfaces.specific.future.AsyncFuture1 "Permalink to this definition")

Type alias for kinds with one type argument.

alias of [`AwaitableFutureN`](#returns.interfaces.specific.future.AwaitableFutureN "returns.interfaces.specific.future.AwaitableFutureN")[`\_FirstType`, `NoReturn`, `NoReturn`]

AsyncFuture2[¶](#returns.interfaces.specific.future.AsyncFuture2 "Permalink to this definition")

Type alias for kinds with two type arguments.

alias of [`AwaitableFutureN`](#returns.interfaces.specific.future.AwaitableFutureN "returns.interfaces.specific.future.AwaitableFutureN")[`\_FirstType`, `\_SecondType`, `NoReturn`]

AsyncFuture3[¶](#returns.interfaces.specific.future.AsyncFuture3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`AwaitableFutureN`](#returns.interfaces.specific.future.AwaitableFutureN "returns.interfaces.specific.future.AwaitableFutureN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

*class* FutureBasedN[[source]](_modules/returns/interfaces/specific/future.html#FutureBasedN)[¶](#returns.interfaces.specific.future.FutureBasedN "Permalink to this definition")

Bases: [`FutureLikeN`](#returns.interfaces.specific.future.FutureLikeN "returns.interfaces.specific.future.FutureLikeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`], [`AwaitableFutureN`](#returns.interfaces.specific.future.AwaitableFutureN "returns.interfaces.specific.future.AwaitableFutureN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

Base type for real `Future` objects.

They can be awaited.

FutureBased1[¶](#returns.interfaces.specific.future.FutureBased1 "Permalink to this definition")

Type alias for kinds with one type argument.

alias of [`FutureBasedN`](#returns.interfaces.specific.future.FutureBasedN "returns.interfaces.specific.future.FutureBasedN")[`\_FirstType`, `NoReturn`, `NoReturn`]

FutureBased2[¶](#returns.interfaces.specific.future.FutureBased2 "Permalink to this definition")

Type alias for kinds with two type arguments.

alias of [`FutureBasedN`](#returns.interfaces.specific.future.FutureBasedN "returns.interfaces.specific.future.FutureBasedN")[`\_FirstType`, `\_SecondType`, `NoReturn`]

FutureBased3[¶](#returns.interfaces.specific.future.FutureBased3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`FutureBasedN`](#returns.interfaces.specific.future.FutureBasedN "returns.interfaces.specific.future.FutureBasedN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

#### FutureResult specific[¶](#futureresult-specific "Permalink to this heading")

 classDiagram

 FutureBasedN <|-- FutureResultBasedN

 FutureLikeN <|-- FutureResultLikeN

 FutureResultLikeN <|-- FutureResultBasedN

 IOResultLikeN <|-- FutureResultLikeN

 Represents the base interfaces for types that do fear-some async operations.

This type means that `FutureResult` can (and will!) fail with exceptions.

Use this type to mark that this specific async opetaion can fail.

*class* FutureResultLikeN[[source]](_modules/returns/interfaces/specific/future_result.html#FutureResultLikeN)[¶](#returns.interfaces.specific.future_result.FutureResultLikeN "Permalink to this definition")

Bases: [`FutureLikeN`](#returns.interfaces.specific.future.FutureLikeN "returns.interfaces.specific.future.FutureLikeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`], [`IOResultLikeN`](#returns.interfaces.specific.ioresult.IOResultLikeN "returns.interfaces.specific.ioresult.IOResultLikeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

Base type for ones that does look like `FutureResult`.

But at the time this is not a real `Future` and cannot be awaited.

It is also cannot be unwrapped, because it is not a real `IOResult`.

*abstract* bind\_future\_result(*function*)[[source]](_modules/returns/interfaces/specific/future_result.html#FutureResultLikeN.bind_future_result)[¶](#returns.interfaces.specific.future_result.FutureResultLikeN.bind_future_result "Permalink to this definition")

Allows to bind `FutureResult` functions over a container.

Parameters:

* **self** (`TypeVar`(`\_FutureResultLikeType`, bound= FutureResultLikeN)) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], [`FutureResult`](index.html#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`)]]) –

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_FutureResultLikeType`, bound= FutureResultLikeN), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

*abstract* bind\_async\_future\_result(*function*)[[source]](_modules/returns/interfaces/specific/future_result.html#FutureResultLikeN.bind_async_future_result)[¶](#returns.interfaces.specific.future_result.FutureResultLikeN.bind_async_future_result "Permalink to this definition")

Allows to bind async `FutureResult` functions over container.

Parameters:

* **self** (`TypeVar`(`\_FutureResultLikeType`, bound= FutureResultLikeN)) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], `Awaitable`[[`FutureResult`](index.html#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`)]]]) –

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_FutureResultLikeType`, bound= FutureResultLikeN), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

*abstract classmethod* from\_failed\_future(*inner\_value*)[[source]](_modules/returns/interfaces/specific/future_result.html#FutureResultLikeN.from_failed_future)[¶](#returns.interfaces.specific.future_result.FutureResultLikeN.from_failed_future "Permalink to this definition")

Creates new container from a failed `Future`.

Parameters:

**inner\_value** ([`Future`](index.html#returns.future.Future "returns.future.Future")[`TypeVar`(`\_ErrorType`)]) – 

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_FutureResultLikeType`, bound= FutureResultLikeN), `TypeVar`(`\_FirstType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_ThirdType`)]

*classmethod* from\_future\_result(*inner\_value*)[[source]](_modules/returns/interfaces/specific/future_result.html#FutureResultLikeN.from_future_result)[¶](#returns.interfaces.specific.future_result.FutureResultLikeN.from_future_result "Permalink to this definition")

Creates container from `FutureResult` instance.

Parameters:

**inner\_value** ([`FutureResult`](index.html#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_ValueType`), `TypeVar`(`\_ErrorType`)]) – 

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_FutureResultLikeType`, bound= FutureResultLikeN), `TypeVar`(`\_ValueType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_ThirdType`)]

FutureResultLike2[¶](#returns.interfaces.specific.future_result.FutureResultLike2 "Permalink to this definition")

Type alias for kinds with two type arguments.

alias of [`FutureResultLikeN`](#returns.interfaces.specific.future_result.FutureResultLikeN "returns.interfaces.specific.future_result.FutureResultLikeN")[`\_FirstType`, `\_SecondType`, `NoReturn`]

FutureResultLike3[¶](#returns.interfaces.specific.future_result.FutureResultLike3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`FutureResultLikeN`](#returns.interfaces.specific.future_result.FutureResultLikeN "returns.interfaces.specific.future_result.FutureResultLikeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

*class* FutureResultBasedN[[source]](_modules/returns/interfaces/specific/future_result.html#FutureResultBasedN)[¶](#returns.interfaces.specific.future_result.FutureResultBasedN "Permalink to this definition")

Bases: [`FutureBasedN`](#returns.interfaces.specific.future.FutureBasedN "returns.interfaces.specific.future.FutureBasedN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`], [`FutureResultLikeN`](#returns.interfaces.specific.future_result.FutureResultLikeN "returns.interfaces.specific.future_result.FutureResultLikeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

Base type for real `FutureResult` objects.

They can be awaited.

Still cannot be unwrapped.

FutureResultBased2[¶](#returns.interfaces.specific.future_result.FutureResultBased2 "Permalink to this definition")

Type alias for kinds with two type arguments.

alias of [`FutureResultBasedN`](#returns.interfaces.specific.future_result.FutureResultBasedN "returns.interfaces.specific.future_result.FutureResultBasedN")[`\_FirstType`, `\_SecondType`, `NoReturn`]

FutureResultBased3[¶](#returns.interfaces.specific.future_result.FutureResultBased3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`FutureResultBasedN`](#returns.interfaces.specific.future_result.FutureResultBasedN "returns.interfaces.specific.future_result.FutureResultBasedN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

#### Reader specific[¶](#reader-specific "Permalink to this heading")

 classDiagram

 CallableReader2 <|-- ReaderBased2

 ContainerN <|-- ReaderLike2

 ContainerN <|-- ReaderLike3

 Contextable <|-- CallableReader2

 Contextable <|-- CallableReader3

 Generic <|-- Contextable

 LawSpecDef <|-- \_LawSpec

 Lawful <|-- ReaderBased2

 ReaderLike2 <|-- CallableReader2

 ReaderLike3 <|-- CallableReader3

 This module is special.

`Reader` does not produce `ReaderLikeN` interface as other containers.

Because `Reader` can be used with two or three type arguments:

- `RequiresContext[value, env]`

- `RequiresContextResult[value, error, env]`

Because the second type argument changes its meaning

based on the used `KindN` instance,

we need to have two separate interfaces for two separate use-cases:

- `ReaderLike2` is used for types where the second type argument is `env`

- `ReaderLike3` is used for types where the third type argument is `env`

We also have two methods and two poinfree helpers

for `bind\_context` composition: one for each interface.

Furthermore, `Reader` cannot have `ReaderLike1` type,

because we need both `value` and `env` types at all cases.

See also

* <https://github.com/dry-python/returns/issues/485>

*class* Contextable[[source]](_modules/returns/interfaces/specific/reader.html#Contextable)[¶](#returns.interfaces.specific.reader.Contextable "Permalink to this definition")

Bases: `Generic`[`\_ValueType`, `\_EnvType`]

Special type we use as a base one for all callble `Reader` instances.

It only has a single method.

And is a base type for every single one of them.

But, each `Reader` defines the return type differently.

For example:

* `Reader` has just `\_ReturnType`

* `ReaderResult` has `Result[\_FirstType, \_SecondType]`

* `ReaderIOResult` has `IOResult[\_FirstType, \_SecondType]`

And so on.

*class* ReaderLike2[[source]](_modules/returns/interfaces/specific/reader.html#ReaderLike2)[¶](#returns.interfaces.specific.reader.ReaderLike2 "Permalink to this definition")

Bases: [`ContainerN`](#returns.interfaces.container.ContainerN "returns.interfaces.container.ContainerN")[`\_FirstType`, `\_SecondType`, `NoReturn`]

Reader interface for `Kind2` based types.

It has two type arguments and treats the second type argument as env type.

*abstract property* no\_args*: NoDeps*[¶](#returns.interfaces.specific.reader.ReaderLike2.no_args "Permalink to this definition")

Is required to call `Reader` with no explicit arguments.

:param self:

:type self: `TypeVar`(`\_ReaderLike2Type`, bound= ReaderLike2)

*abstract* bind\_context(*function*)[[source]](_modules/returns/interfaces/specific/reader.html#ReaderLike2.bind_context)[¶](#returns.interfaces.specific.reader.ReaderLike2.bind_context "Permalink to this definition")

Allows to apply a wrapped function over a `Reader` container.

Parameters:

* **self** (`TypeVar`(`\_ReaderLike2Type`, bound= ReaderLike2)) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], [`RequiresContext`](index.html#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[`TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`)]]) –

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ReaderLike2Type`, bound= ReaderLike2), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `Any`]

*abstract* modify\_env(*function*)[[source]](_modules/returns/interfaces/specific/reader.html#ReaderLike2.modify_env)[¶](#returns.interfaces.specific.reader.ReaderLike2.modify_env "Permalink to this definition")

Transforms the environment before calling the container.

Parameters:

* **self** (`TypeVar`(`\_ReaderLike2Type`, bound= ReaderLike2)) –

* **function** (`Callable`[[`TypeVar`(`\_UpdatedType`)], `TypeVar`(`\_SecondType`)]) –

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ReaderLike2Type`, bound= ReaderLike2), `TypeVar`(`\_FirstType`), `TypeVar`(`\_UpdatedType`), `Any`]

*abstract classmethod* ask()[[source]](_modules/returns/interfaces/specific/reader.html#ReaderLike2.ask)[¶](#returns.interfaces.specific.reader.ReaderLike2.ask "Permalink to this definition")

Returns the dependencies inside the container.

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ReaderLike2Type`, bound= ReaderLike2), `TypeVar`(`\_SecondType`), `TypeVar`(`\_SecondType`), `Any`]

*abstract classmethod* from\_context(*inner\_value*)[[source]](_modules/returns/interfaces/specific/reader.html#ReaderLike2.from_context)[¶](#returns.interfaces.specific.reader.ReaderLike2.from_context "Permalink to this definition")

Unit method to create new containers from successful `Reader`.

Parameters:

**inner\_value** ([`RequiresContext`](index.html#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[`TypeVar`(`\_ValueType`), `TypeVar`(`\_EnvType`)]) – 

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ReaderLike2Type`, bound= ReaderLike2), `TypeVar`(`\_ValueType`), `TypeVar`(`\_EnvType`), `Any`]

*class* CallableReader2[[source]](_modules/returns/interfaces/specific/reader.html#CallableReader2)[¶](#returns.interfaces.specific.reader.CallableReader2 "Permalink to this definition")

Bases: [`ReaderLike2`](#returns.interfaces.specific.reader.ReaderLike2 "returns.interfaces.specific.reader.ReaderLike2")[`\_FirstType`, `\_SecondType`], [`Contextable`](#returns.interfaces.specific.reader.Contextable "returns.interfaces.specific.reader.Contextable")[`\_ValueType`, `\_EnvType`]

Intermediate interface for `ReaderLike2` + `\_\_call\_\_` method.

Has 4 type variables to type `Reader` and `\_\_call\_\_` independently.

Since, we don’t have any other fancy ways of doing it.

Should not be used directly

other than defining your own `Reader` interfaces.

*class* ReaderLike3[[source]](_modules/returns/interfaces/specific/reader.html#ReaderLike3)[¶](#returns.interfaces.specific.reader.ReaderLike3 "Permalink to this definition")

Bases: [`ContainerN`](#returns.interfaces.container.ContainerN "returns.interfaces.container.ContainerN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

Reader interface for `Kind3` based types.

It has three type arguments and treats the third type argument as env type.

The second type argument is not used here.

*abstract property* no\_args*: Any*[¶](#returns.interfaces.specific.reader.ReaderLike3.no_args "Permalink to this definition")

Is required to call `Reader` with no explicit arguments.

:param self:

:type self: `TypeVar`(`\_ReaderLike3Type`, bound= ReaderLike3)

*abstract* bind\_context(*function*)[[source]](_modules/returns/interfaces/specific/reader.html#ReaderLike3.bind_context)[¶](#returns.interfaces.specific.reader.ReaderLike3.bind_context "Permalink to this definition")

Allows to apply a wrapped function over a `Reader` container.

Parameters:

* **self** (`TypeVar`(`\_ReaderLike3Type`, bound= ReaderLike3)) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], [`RequiresContext`](index.html#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[`TypeVar`(`\_UpdatedType`), `TypeVar`(`\_ThirdType`)]]) –

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ReaderLike3Type`, bound= ReaderLike3), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

*abstract* modify\_env(*function*)[[source]](_modules/returns/interfaces/specific/reader.html#ReaderLike3.modify_env)[¶](#returns.interfaces.specific.reader.ReaderLike3.modify_env "Permalink to this definition")

Transforms the environment before calling the container.

Parameters:

* **self** (`TypeVar`(`\_ReaderLike3Type`, bound= ReaderLike3)) –

* **function** (`Callable`[[`TypeVar`(`\_UpdatedType`)], `TypeVar`(`\_ThirdType`)]) –

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ReaderLike3Type`, bound= ReaderLike3), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_UpdatedType`)]

*abstract classmethod* ask()[[source]](_modules/returns/interfaces/specific/reader.html#ReaderLike3.ask)[¶](#returns.interfaces.specific.reader.ReaderLike3.ask "Permalink to this definition")

Returns the dependencies inside the container.

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ReaderLike3Type`, bound= ReaderLike3), `TypeVar`(`\_ThirdType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

*abstract classmethod* from\_context(*inner\_value*)[[source]](_modules/returns/interfaces/specific/reader.html#ReaderLike3.from_context)[¶](#returns.interfaces.specific.reader.ReaderLike3.from_context "Permalink to this definition")

Unit method to create new containers from successful `Reader`.

Parameters:

**inner\_value** ([`RequiresContext`](index.html#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[`TypeVar`(`\_ValueType`), `TypeVar`(`\_EnvType`)]) – 

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ReaderLike3Type`, bound= ReaderLike3), `TypeVar`(`\_ValueType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_EnvType`)]

*class* CallableReader3[[source]](_modules/returns/interfaces/specific/reader.html#CallableReader3)[¶](#returns.interfaces.specific.reader.CallableReader3 "Permalink to this definition")

Bases: [`ReaderLike3`](#returns.interfaces.specific.reader.ReaderLike3 "returns.interfaces.specific.reader.ReaderLike3")[`\_FirstType`, `\_SecondType`, `\_ThirdType`], [`Contextable`](#returns.interfaces.specific.reader.Contextable "returns.interfaces.specific.reader.Contextable")[`\_ValueType`, `\_EnvType`]

Intermediate interface for `ReaderLike3` + `\_\_call\_\_` method.

Has 5 type variables to type `Reader` and `\_\_call\_\_` independently.

Since, we don’t have any other fancy ways of doing it.

Should not be used directly

other than defining your own `Reader` interfaces.

*final class* \_LawSpec[[source]](_modules/returns/interfaces/specific/reader.html#_LawSpec)[¶](#returns.interfaces.specific.reader._LawSpec "Permalink to this definition")

Bases: [`LawSpecDef`](index.html#returns.primitives.laws.LawSpecDef "returns.primitives.laws.LawSpecDef")

Concrete laws for `ReaderBased2`.

See: <https://github.com/haskell/mtl/pull/61/files>

*static* purity\_law(*container*, *env*)[[source]](_modules/returns/interfaces/specific/reader.html#_LawSpec.purity_law)[¶](#returns.interfaces.specific.reader._LawSpec.purity_law "Permalink to this definition")

Calling a `Reader` twice has the same result with the same env.

Parameters:

* **container** ([`ReaderBased2`](#returns.interfaces.specific.reader.ReaderBased2 "returns.interfaces.specific.reader.ReaderBased2")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`)]) –

* **env** (`TypeVar`(`\_SecondType`)) –

Return type:

`None`

*static* asking\_law(*container*, *env*)[[source]](_modules/returns/interfaces/specific/reader.html#_LawSpec.asking_law)[¶](#returns.interfaces.specific.reader._LawSpec.asking_law "Permalink to this definition")

Asking for an env, always returns the env.

Parameters:

* **container** ([`ReaderBased2`](#returns.interfaces.specific.reader.ReaderBased2 "returns.interfaces.specific.reader.ReaderBased2")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`)]) –

* **env** (`TypeVar`(`\_SecondType`)) –

Return type:

`None`

*class* ReaderBased2[[source]](_modules/returns/interfaces/specific/reader.html#ReaderBased2)[¶](#returns.interfaces.specific.reader.ReaderBased2 "Permalink to this definition")

Bases: [`CallableReader2`](#returns.interfaces.specific.reader.CallableReader2 "returns.interfaces.specific.reader.CallableReader2")[`\_FirstType`, `\_SecondType`, `\_FirstType`, `\_SecondType`], [`Lawful`](index.html#returns.primitives.laws.Lawful "returns.primitives.laws.Lawful")[`ReaderBased2[\_FirstType, \_SecondType]`]

This interface is very specific to our `Reader` type.

The only thing that differs from `ReaderLike2` is that we know

the specific types for its `\_\_call\_\_` method.

\_laws*: `ClassVar`[`Sequence`[[`Law`](index.html#returns.primitives.laws.Law "returns.primitives.laws.Law")]]* *= (<returns.primitives.laws.Law2 object>, <returns.primitives.laws.Law2 object>)*[¶](#returns.interfaces.specific.reader.ReaderBased2._laws "Permalink to this definition")

Some classes and interfaces might have laws, some might not have any.

#### ReaderResult specific[¶](#readerresult-specific "Permalink to this heading")

 classDiagram

 CallableReader3 <|-- ReaderResultBasedN

 LawSpecDef <|-- \_LawSpec

 Lawful <|-- ReaderResultBasedN

 ReaderLike3 <|-- ReaderResultLikeN

 ReaderResultLikeN <|-- ReaderResultBasedN

 ResultLikeN <|-- ReaderResultLikeN

 

*class* ReaderResultLikeN[[source]](_modules/returns/interfaces/specific/reader_result.html#ReaderResultLikeN)[¶](#returns.interfaces.specific.reader_result.ReaderResultLikeN "Permalink to this definition")

Bases: [`ReaderLike3`](#returns.interfaces.specific.reader.ReaderLike3 "returns.interfaces.specific.reader.ReaderLike3")[`\_FirstType`, `\_SecondType`, `\_ThirdType`], [`ResultLikeN`](#returns.interfaces.specific.result.ResultLikeN "returns.interfaces.specific.result.ResultLikeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

Base interface for all types that do look like `ReaderResult` instance.

Cannot be called.

*abstract* bind\_context\_result(*function*)[[source]](_modules/returns/interfaces/specific/reader_result.html#ReaderResultLikeN.bind_context_result)[¶](#returns.interfaces.specific.reader_result.ReaderResultLikeN.bind_context_result "Permalink to this definition")

Binds a `ReaderResult` returning function over a container.

Parameters:

* **self** (`TypeVar`(`\_ReaderResultLikeType`, bound= ReaderResultLikeN)) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], [`RequiresContextResult`](index.html#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]) –

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ReaderResultLikeType`, bound= ReaderResultLikeN), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

*abstract classmethod* from\_failed\_context(*inner\_value*)[[source]](_modules/returns/interfaces/specific/reader_result.html#ReaderResultLikeN.from_failed_context)[¶](#returns.interfaces.specific.reader_result.ReaderResultLikeN.from_failed_context "Permalink to this definition")

Unit method to create new containers from failed `Reader`.

Parameters:

**inner\_value** ([`RequiresContext`](index.html#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[`TypeVar`(`\_ErrorType`), `TypeVar`(`\_EnvType`)]) – 

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ReaderResultLikeType`, bound= ReaderResultLikeN), `TypeVar`(`\_FirstType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_EnvType`)]

*abstract classmethod* from\_result\_context(*inner\_value*)[[source]](_modules/returns/interfaces/specific/reader_result.html#ReaderResultLikeN.from_result_context)[¶](#returns.interfaces.specific.reader_result.ReaderResultLikeN.from_result_context "Permalink to this definition")

Unit method to create new containers from `ReaderResult`.

Parameters:

**inner\_value** ([`RequiresContextResult`](index.html#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`TypeVar`(`\_ValueType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_EnvType`)]) – 

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ReaderResultLikeType`, bound= ReaderResultLikeN), `TypeVar`(`\_ValueType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_EnvType`)]

ReaderResultLike3[¶](#returns.interfaces.specific.reader_result.ReaderResultLike3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`ReaderResultLikeN`](#returns.interfaces.specific.reader_result.ReaderResultLikeN "returns.interfaces.specific.reader_result.ReaderResultLikeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

*final class* \_LawSpec[[source]](_modules/returns/interfaces/specific/reader_result.html#_LawSpec)[¶](#returns.interfaces.specific.reader_result._LawSpec "Permalink to this definition")

Bases: [`LawSpecDef`](index.html#returns.primitives.laws.LawSpecDef "returns.primitives.laws.LawSpecDef")

Concrete laws for `ReaderResulBasedN`.

See: <https://github.com/haskell/mtl/pull/61/files>

*static* purity\_law(*container*, *env*)[[source]](_modules/returns/interfaces/specific/reader_result.html#_LawSpec.purity_law)[¶](#returns.interfaces.specific.reader_result._LawSpec.purity_law "Permalink to this definition")

Calling a `Reader` twice has the same result with the same env.

Parameters:

* **container** ([`ReaderResultBasedN`](#returns.interfaces.specific.reader_result.ReaderResultBasedN "returns.interfaces.specific.reader_result.ReaderResultBasedN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) –

* **env** (`TypeVar`(`\_ThirdType`)) –

Return type:

`None`

*static* asking\_law(*container*, *env*)[[source]](_modules/returns/interfaces/specific/reader_result.html#_LawSpec.asking_law)[¶](#returns.interfaces.specific.reader_result._LawSpec.asking_law "Permalink to this definition")

Asking for an env, always returns the env.

Parameters:

* **container** ([`ReaderResultBasedN`](#returns.interfaces.specific.reader_result.ReaderResultBasedN "returns.interfaces.specific.reader_result.ReaderResultBasedN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) –

* **env** (`TypeVar`(`\_ThirdType`)) –

Return type:

`None`

*class* ReaderResultBasedN[[source]](_modules/returns/interfaces/specific/reader_result.html#ReaderResultBasedN)[¶](#returns.interfaces.specific.reader_result.ReaderResultBasedN "Permalink to this definition")

Bases: [`ReaderResultLikeN`](#returns.interfaces.specific.reader_result.ReaderResultLikeN "returns.interfaces.specific.reader_result.ReaderResultLikeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`], [`CallableReader3`](#returns.interfaces.specific.reader.CallableReader3 "returns.interfaces.specific.reader.CallableReader3")[`\_FirstType`, `\_SecondType`, `\_ThirdType`, `Result[\_FirstType, \_SecondType]`, `\_ThirdType`], [`Lawful`](index.html#returns.primitives.laws.Lawful "returns.primitives.laws.Lawful")[`ReaderResultBasedN[\_FirstType, \_SecondType, \_ThirdType]`]

This interface is very specific to our `ReaderResult` type.

The only thing that differs from `ReaderResultLikeN` is that we know

the specific types for its `\_\_call\_\_` method.

In this case the return type of `\_\_call\_\_` is `Result`.

\_laws*: `ClassVar`[`Sequence`[[`Law`](index.html#returns.primitives.laws.Law "returns.primitives.laws.Law")]]* *= (<returns.primitives.laws.Law2 object>, <returns.primitives.laws.Law2 object>)*[¶](#returns.interfaces.specific.reader_result.ReaderResultBasedN._laws "Permalink to this definition")

Some classes and interfaces might have laws, some might not have any.

ReaderResultBased3[¶](#returns.interfaces.specific.reader_result.ReaderResultBased3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`ReaderResultBasedN`](#returns.interfaces.specific.reader_result.ReaderResultBasedN "returns.interfaces.specific.reader_result.ReaderResultBasedN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

#### ReaderIOResult specific[¶](#readerioresult-specific "Permalink to this heading")

 classDiagram

 CallableReader3 <|-- ReaderIOResultBasedN

 IOResultLikeN <|-- ReaderIOResultLikeN

 LawSpecDef <|-- \_LawSpec

 Lawful <|-- ReaderIOResultBasedN

 ReaderIOResultLikeN <|-- ReaderIOResultBasedN

 ReaderResultLikeN <|-- ReaderIOResultLikeN

 

*class* ReaderIOResultLikeN[[source]](_modules/returns/interfaces/specific/reader_ioresult.html#ReaderIOResultLikeN)[¶](#returns.interfaces.specific.reader_ioresult.ReaderIOResultLikeN "Permalink to this definition")

Bases: [`ReaderResultLikeN`](#returns.interfaces.specific.reader_result.ReaderResultLikeN "returns.interfaces.specific.reader_result.ReaderResultLikeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`], [`IOResultLikeN`](#returns.interfaces.specific.ioresult.IOResultLikeN "returns.interfaces.specific.ioresult.IOResultLikeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

Base interface for all types that do look like `ReaderIOResult` instance.

Cannot be called.

*abstract* bind\_context\_ioresult(*function*)[[source]](_modules/returns/interfaces/specific/reader_ioresult.html#ReaderIOResultLikeN.bind_context_ioresult)[¶](#returns.interfaces.specific.reader_ioresult.ReaderIOResultLikeN.bind_context_ioresult "Permalink to this definition")

Binds a `ReaderIOResult` returning function over a container.

Parameters:

* **self** (`TypeVar`(`\_ReaderIOResultLikeType`, bound= ReaderIOResultLikeN)) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], [`RequiresContextIOResult`](index.html#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]) –

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ReaderIOResultLikeType`, bound= ReaderIOResultLikeN), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

*abstract classmethod* from\_ioresult\_context(*inner\_value*)[[source]](_modules/returns/interfaces/specific/reader_ioresult.html#ReaderIOResultLikeN.from_ioresult_context)[¶](#returns.interfaces.specific.reader_ioresult.ReaderIOResultLikeN.from_ioresult_context "Permalink to this definition")

Unit method to create new containers from `ReaderIOResult`.

Parameters:

**inner\_value** ([`RequiresContextIOResult`](index.html#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_ValueType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_EnvType`)]) – 

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ReaderIOResultLikeType`, bound= ReaderIOResultLikeN), `TypeVar`(`\_ValueType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_EnvType`)]

ReaderIOResultLike3[¶](#returns.interfaces.specific.reader_ioresult.ReaderIOResultLike3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`ReaderIOResultLikeN`](#returns.interfaces.specific.reader_ioresult.ReaderIOResultLikeN "returns.interfaces.specific.reader_ioresult.ReaderIOResultLikeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

*final class* \_LawSpec[[source]](_modules/returns/interfaces/specific/reader_ioresult.html#_LawSpec)[¶](#returns.interfaces.specific.reader_ioresult._LawSpec "Permalink to this definition")

Bases: [`LawSpecDef`](index.html#returns.primitives.laws.LawSpecDef "returns.primitives.laws.LawSpecDef")

Concrete laws for `ReaderIOResultBasedN`.

See: <https://github.com/haskell/mtl/pull/61/files>

*static* asking\_law(*container*, *env*)[[source]](_modules/returns/interfaces/specific/reader_ioresult.html#_LawSpec.asking_law)[¶](#returns.interfaces.specific.reader_ioresult._LawSpec.asking_law "Permalink to this definition")

Asking for an env, always returns the env.

Parameters:

* **container** ([`ReaderIOResultBasedN`](#returns.interfaces.specific.reader_ioresult.ReaderIOResultBasedN "returns.interfaces.specific.reader_ioresult.ReaderIOResultBasedN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) –

* **env** (`TypeVar`(`\_ThirdType`)) –

Return type:

`None`

*class* ReaderIOResultBasedN[[source]](_modules/returns/interfaces/specific/reader_ioresult.html#ReaderIOResultBasedN)[¶](#returns.interfaces.specific.reader_ioresult.ReaderIOResultBasedN "Permalink to this definition")

Bases: [`ReaderIOResultLikeN`](#returns.interfaces.specific.reader_ioresult.ReaderIOResultLikeN "returns.interfaces.specific.reader_ioresult.ReaderIOResultLikeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`], [`CallableReader3`](#returns.interfaces.specific.reader.CallableReader3 "returns.interfaces.specific.reader.CallableReader3")[`\_FirstType`, `\_SecondType`, `\_ThirdType`, `IOResult[\_FirstType, \_SecondType]`, `\_ThirdType`], [`Lawful`](index.html#returns.primitives.laws.Lawful "returns.primitives.laws.Lawful")[`ReaderIOResultBasedN[\_FirstType, \_SecondType, \_ThirdType]`]

This interface is very specific to our `ReaderIOResult` type.

The only thing that differs from `ReaderIOResultLikeN` is that we know

the specific types for its `\_\_call\_\_` method.

In this case the return type of `\_\_call\_\_` is `IOResult`.

\_laws*: `ClassVar`[`Sequence`[[`Law`](index.html#returns.primitives.laws.Law "returns.primitives.laws.Law")]]* *= (<returns.primitives.laws.Law2 object>,)*[¶](#returns.interfaces.specific.reader_ioresult.ReaderIOResultBasedN._laws "Permalink to this definition")

Some classes and interfaces might have laws, some might not have any.

ReaderIOResultBased3[¶](#returns.interfaces.specific.reader_ioresult.ReaderIOResultBased3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`ReaderIOResultBasedN`](#returns.interfaces.specific.reader_ioresult.ReaderIOResultBasedN "returns.interfaces.specific.reader_ioresult.ReaderIOResultBasedN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

#### ReaderFutureResult specific[¶](#readerfutureresult-specific "Permalink to this heading")

 classDiagram

 CallableReader3 <|-- ReaderFutureResultBasedN

 FutureResultLikeN <|-- ReaderFutureResultLikeN

 LawSpecDef <|-- \_LawSpec

 Lawful <|-- ReaderFutureResultBasedN

 ReaderFutureResultLikeN <|-- ReaderFutureResultBasedN

 ReaderIOResultLikeN <|-- ReaderFutureResultLikeN

 

*class* ReaderFutureResultLikeN[[source]](_modules/returns/interfaces/specific/reader_future_result.html#ReaderFutureResultLikeN)[¶](#returns.interfaces.specific.reader_future_result.ReaderFutureResultLikeN "Permalink to this definition")

Bases: [`ReaderIOResultLikeN`](#returns.interfaces.specific.reader_ioresult.ReaderIOResultLikeN "returns.interfaces.specific.reader_ioresult.ReaderIOResultLikeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`], [`FutureResultLikeN`](#returns.interfaces.specific.future_result.FutureResultLikeN "returns.interfaces.specific.future_result.FutureResultLikeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

Interface for all types that do look like `ReaderFutureResult` instance.

Cannot be called.

*abstract* bind\_context\_future\_result(*function*)[[source]](_modules/returns/interfaces/specific/reader_future_result.html#ReaderFutureResultLikeN.bind_context_future_result)[¶](#returns.interfaces.specific.reader_future_result.ReaderFutureResultLikeN.bind_context_future_result "Permalink to this definition")

Bind a `ReaderFutureResult` returning function over a container.

Parameters:

* **self** (`TypeVar`(`\_ReaderFutureResultLikeType`, bound= ReaderFutureResultLikeN)) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], [`RequiresContextFutureResult`](index.html#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]) –

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ReaderFutureResultLikeType`, bound= ReaderFutureResultLikeN), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

*abstract* bind\_async\_context\_future\_result(*function*)[[source]](_modules/returns/interfaces/specific/reader_future_result.html#ReaderFutureResultLikeN.bind_async_context_future_result)[¶](#returns.interfaces.specific.reader_future_result.ReaderFutureResultLikeN.bind_async_context_future_result "Permalink to this definition")

Bind async `ReaderFutureResult` function.

Parameters:

* **self** (`TypeVar`(`\_ReaderFutureResultLikeType`, bound= ReaderFutureResultLikeN)) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], `Awaitable`[[`RequiresContextFutureResult`](index.html#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]]) –

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ReaderFutureResultLikeType`, bound= ReaderFutureResultLikeN), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

*abstract classmethod* from\_future\_result\_context(*inner\_value*)[[source]](_modules/returns/interfaces/specific/reader_future_result.html#ReaderFutureResultLikeN.from_future_result_context)[¶](#returns.interfaces.specific.reader_future_result.ReaderFutureResultLikeN.from_future_result_context "Permalink to this definition")

Unit method to create new containers from `ReaderFutureResult`.

Parameters:

**inner\_value** ([`RequiresContextFutureResult`](index.html#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_ValueType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_EnvType`)]) – 

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ReaderFutureResultLikeType`, bound= ReaderFutureResultLikeN), `TypeVar`(`\_ValueType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_EnvType`)]

ReaderFutureResultLike3[¶](#returns.interfaces.specific.reader_future_result.ReaderFutureResultLike3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`ReaderFutureResultLikeN`](#returns.interfaces.specific.reader_future_result.ReaderFutureResultLikeN "returns.interfaces.specific.reader_future_result.ReaderFutureResultLikeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

*final class* \_LawSpec[[source]](_modules/returns/interfaces/specific/reader_future_result.html#_LawSpec)[¶](#returns.interfaces.specific.reader_future_result._LawSpec "Permalink to this definition")

Bases: [`LawSpecDef`](index.html#returns.primitives.laws.LawSpecDef "returns.primitives.laws.LawSpecDef")

Concrete laws for `ReaderFutureResultBasedN`.

See: <https://github.com/haskell/mtl/pull/61/files>

*static* asking\_law(*container*, *env*)[[source]](_modules/returns/interfaces/specific/reader_future_result.html#_LawSpec.asking_law)[¶](#returns.interfaces.specific.reader_future_result._LawSpec.asking_law "Permalink to this definition")

Asking for an env, always returns the env.

Parameters:

* **container** ([`ReaderFutureResultBasedN`](#returns.interfaces.specific.reader_future_result.ReaderFutureResultBasedN "returns.interfaces.specific.reader_future_result.ReaderFutureResultBasedN")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) –

* **env** (`TypeVar`(`\_ThirdType`)) –

Return type:

`None`

*class* ReaderFutureResultBasedN[[source]](_modules/returns/interfaces/specific/reader_future_result.html#ReaderFutureResultBasedN)[¶](#returns.interfaces.specific.reader_future_result.ReaderFutureResultBasedN "Permalink to this definition")

Bases: [`ReaderFutureResultLikeN`](#returns.interfaces.specific.reader_future_result.ReaderFutureResultLikeN "returns.interfaces.specific.reader_future_result.ReaderFutureResultLikeN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`], [`CallableReader3`](#returns.interfaces.specific.reader.CallableReader3 "returns.interfaces.specific.reader.CallableReader3")[`\_FirstType`, `\_SecondType`, `\_ThirdType`, `FutureResult[\_FirstType, \_SecondType]`, `\_ThirdType`], [`Lawful`](index.html#returns.primitives.laws.Lawful "returns.primitives.laws.Lawful")[`ReaderFutureResultBasedN[\_FirstType, \_SecondType, \_ThirdType]`]

This interface is very specific to our `ReaderFutureResult` type.

The only thing that differs from `ReaderFutureResultLikeN`

is that we know the specific types for its `\_\_call\_\_` method.

In this case the return type of `\_\_call\_\_` is `FutureResult`.

\_laws*: `ClassVar`[`Sequence`[[`Law`](index.html#returns.primitives.laws.Law "returns.primitives.laws.Law")]]* *= (<returns.primitives.laws.Law2 object>,)*[¶](#returns.interfaces.specific.reader_future_result.ReaderFutureResultBasedN._laws "Permalink to this definition")

Some classes and interfaces might have laws, some might not have any.

ReaderFutureResultBased3[¶](#returns.interfaces.specific.reader_future_result.ReaderFutureResultBased3 "Permalink to this definition")

Type alias for kinds with three type arguments.

alias of [`ReaderFutureResultBasedN`](#returns.interfaces.specific.reader_future_result.ReaderFutureResultBasedN "returns.interfaces.specific.reader_future_result.ReaderFutureResultBasedN")[`\_FirstType`, `\_SecondType`, `\_ThirdType`]

Maybe[¶](#maybe "Permalink to this heading")

--------------------------------------------

The `Maybe` container is used when a series of computations

could return `None` at any point.

### Maybe container[¶](#maybe-container "Permalink to this heading")

`Maybe` consist of two types: `Some` and `Nothing`.

We have a convenient method to create different `Maybe` types

based on just a single value:

```

>>> from returns.maybe import Maybe

>>> assert str(Maybe.from\_optional(1)) == '<Some: 1>'

>>> assert str(Maybe.from\_optional(None)) == '<Nothing>'

```

We also have another method called `.from\_value`

that behaves a bit differently:

```

>>> from returns.maybe import Maybe

>>> assert str(Maybe.from\_value(1)) == '<Some: 1>'

>>> assert str(Maybe.from\_value(None)) == '<Some: None>'

```

#### Usage[¶](#usage "Permalink to this heading")

It might be very useful for complex operations like the following one:

```

>>> from attr import dataclass

>>> from typing import Optional

>>> from returns.maybe import Maybe, Nothing

>>> @dataclass

... class Address(object):

...     street: Optional[str]

>>> @dataclass

... class User(object):

...     address: Optional[Address]

>>> @dataclass

... class Order(object):

...     user: Optional[User]

>>> def get\_street\_address(order: Order) -> Maybe[str]:

...     return Maybe.from\_optional(order.user).bind\_optional(

...         lambda user: user.address,

...     ).bind\_optional(

...         lambda address: address.street,

...     )

>>> with\_address = Order(User(Address('Some street')))

>>> empty\_user = Order(None)

>>> empty\_address = Order(User(None))

>>> empty\_street = Order(User(Address(None)))

>>> str(get\_street\_address(with\_address))  # all fields are not None

'<Some: Some street>'

>>> assert get\_street\_address(empty\_user) == Nothing

>>> assert get\_street\_address(empty\_address) == Nothing

>>> assert get\_street\_address(empty\_street) == Nothing

```

#### Optional type[¶](#optional-type "Permalink to this heading")

One may ask: “How is that different to the `Optional[]` type?”

That’s a really good question!

Consider the same code to get the street name

without `Maybe` and using raw `Optional` values:

```

order: Order  # some existing Order instance

street: Optional[str] = None

if order.user is not None:

    if order.user.address is not None:

        street = order.user.address.street

```

It looks way uglier and can grow even more uglier and complex

when new logic will be introduced.

### Pattern Matching[¶](#pattern-matching "Permalink to this heading")

`Maybe` values can be matched using the new feature of Python 3.10,

[Structural Pattern Matching](https://www.python.org/dev/peps/pep-0622/),

see the example below:

```

from dataclasses import dataclass

from typing import Final

from returns.maybe import Maybe, Nothing, Some

@dataclass

class \_Book(object):

    book\_id: int

    name: str

\_BOOK\_LIST: Final = (

    \_Book(book\_id=1, name='Category Theory for Programmers'),

    \_Book(book\_id=2, name='Fluent Python'),

    \_Book(book\_id=3, name='Learn You Some Erlang for Great Good'),

    \_Book(book\_id=4, name='Learn You a Haskell for Great Good'),

)

def \_find\_book(book\_id: int) -> Maybe[\_Book]:

    for book in \_BOOK\_LIST:

        if book.book\_id == book\_id:

            return Some(book)

    return Nothing

if \_\_name\_\_ == '\_\_main\_\_':

    desired\_book = \_find\_book(2)

    match desired\_book:

        # Matches any `Some` instance that contains a book named `Fluent Python`

        case Some(\_Book(name='Fluent Python')):

            print('"Fluent Python" was found')

        # Matches any `Some` instance and binds its value to the `book` variable

        case Some(book):

            print('Book found: {0}'.format(book.name))

        # Matches `Nothing` instance

        case Maybe.empty:

            print('Not found the desired book!')

```

### Decorators[¶](#decorators "Permalink to this heading")

#### Limitations[¶](#limitations "Permalink to this heading")

Typing will only work correctly

if [our mypy plugin](index.html#mypy-plugins) is used.

This happens due to [mypy issue](https://github.com/python/mypy/issues/3157).

#### maybe[¶](#id2 "Permalink to this heading")

Sometimes we have to deal with functions

that dears to return `Optional` values!

We have to work with it the carefully

and write `if x is not None:` everywhere.

Luckily, we have your back! `maybe` function decorates

any other function that returns `Optional`

and converts it to return `Maybe` instead:

```

>>> from typing import Optional

>>> from returns.maybe import Maybe, Some, maybe

>>> @maybe

... def number(num: int) -> Optional[int]:

...     if num > 0:

...         return num

...     return None

>>> result: Maybe[int] = number(1)

>>> assert result == Some(1)

```

### FAQ[¶](#faq "Permalink to this heading")

#### How can I turn Maybe into Optional again?[¶](#how-can-i-turn-maybe-into-optional-again "Permalink to this heading")

When working with regular Python,

you might need regular `Optional[a]` values.

You can easily get one from your `Maybe` container at any point in time:

```

>>> from returns.maybe import Maybe

>>> assert Maybe.from\_optional(1).value\_or(None) == 1

>>> assert Maybe.from\_optional(None).value\_or(None) == None

```

As you can see, revealed type of `.value\_or(None)` is `Optional[a]`.

Use it a fallback.

#### How to model absence of value vs presence of None value?[¶](#how-to-model-absence-of-value-vs-presence-of-none-value "Permalink to this heading")

Let’s say you have this `dict`: `values = {'a': 1, 'b': None}`

So, you can have two types of `None` here:

* `values.get('b')`

* `values.get('c')`

But, they are different!

The first has explicit `None` value,

the second one has no given key and `None` is used as a default.

You might need to know exactly which case you are dealing with.

For example, in validation.

So, the first thing to remember is that:

```

>>> assert Some(None) != Nothing

```

There’s a special way to work with a type like this:

```

>>> values = {'a': 1, 'b': None}

>>> assert Maybe.from\_value(values).map(lambda d: d.get('a')) == Some(1)

>>> assert Maybe.from\_value(values).map(lambda d: d.get('b')) == Some(None)

```

In contrast, you can ignore both `None` values easily:

```

>>> assert Maybe.from\_value(values).bind\_optional(

...     lambda d: d.get('a'),

... ) == Some(1)

>>> assert Maybe.from\_value(values).bind\_optional(

...     lambda d: d.get('b'),

... ) == Nothing

```

So, how to write a complete check for a value: both present and missing?

```

>>> from typing import Optional, Dict, TypeVar

>>> from returns.maybe import Maybe, Some, Nothing

>>> \_Key = TypeVar('\_Key')

>>> \_Value = TypeVar('\_Value')

>>> def check\_key(

...    heystack: Dict[\_Key, \_Value],

...    needle: \_Key,

... ) -> Maybe[\_Value]:

...     if needle not in heystack:

...         return Nothing

...     return Maybe.from\_value(heystack[needle])  # try with `.from\_optional`

>>> real\_values = {'a': 1}

>>> opt\_values = {'a': 1, 'b': None}

>>> assert check\_key(real\_values, 'a') == Some(1)

>>> assert check\_key(real\_values, 'b') == Nothing

>>> # Type revealed: returns.maybe.Maybe[builtins.int]

>>> assert check\_key(opt\_values, 'a') == Some(1)

>>> assert check\_key(opt\_values, 'b') == Some(None)

>>> assert check\_key(opt\_values, 'c') == Nothing

>>> # Type revealed: returns.maybe.Maybe[Union[builtins.int, None]]

```

Choose wisely between `.from\_value` and `.map`,

and `.from\_optional` and `.bind\_optional`.

They are similar, but do different things.

Note that you can also use [`returns.pipeline.is\_successful()`](index.html#returns.pipeline.is_successful "returns.pipeline.is_successful")

to check if the value is present.

See the

[original issue about Some(None)](https://github.com/dry-python/returns/issues/314)

for more details and the full history.

#### Why there’s no IOMaybe?[¶](#why-there-s-no-iomaybe "Permalink to this heading")

We do have `IOResult`, but we don’t have `IOMaybe`. Why?

Because when dealing with `IO` there are a lot of possible errors.

And `Maybe` represents just `None` and the value.

It is not useful for `IO` related tasks.

So, use `Result` instead, which can represent what happened to your `IO`.

You can convert `Maybe` to `Result`

and back again with special [Converters](index.html#converters).

#### Why Maybe does not have alt method?[¶](#why-maybe-does-not-have-alt-method "Permalink to this heading")

Well, because `Maybe` only has a single failed value:

`Nothing` and it cannot be altered.

But, `Maybe` has [`returns.maybe.Maybe.or\_else\_call()`](#returns.maybe.Maybe.or_else_call "returns.maybe.Maybe.or_else_call") method to call

a passed callback function with zero argument on failed container:

```

>>> from returns.maybe import Some, Nothing

>>> assert Some(1).or\_else\_call(lambda: 2) == 1

>>> assert Nothing.or\_else\_call(lambda: 2) == 2

```

This method is unique to `Maybe` container.

### Further reading[¶](#further-reading "Permalink to this heading")

* [Option Monads in Rust](https://hoverbear.org/blog/option-monads-in-rust/)

* [Option overview in TypeScript](https://gcanti.github.io/fp-ts/modules/Option.ts.html)

* [Maybe not - Rich Hickey](https://www.youtube.com/watch?v=YR5WdGrpoug)

### API Reference[¶](#api-reference "Permalink to this heading")

 classDiagram

 BaseContainer <|-- Maybe

 Maybe <|-- Some

 Maybe <|-- \_Nothing

 MaybeBasedN <|-- Maybe

 SupportsKindN <|-- Maybe

 

*class* Maybe(*inner\_value*)[[source]](_modules/returns/maybe.html#Maybe)[¶](#returns.maybe.Maybe "Permalink to this definition")

Bases: [`BaseContainer`](index.html#returns.primitives.container.BaseContainer "returns.primitives.container.BaseContainer"), [`SupportsKindN`](index.html#returns.primitives.hkt.SupportsKindN "returns.primitives.hkt.SupportsKindN")[[`Maybe`](#returns.maybe.Maybe "returns.maybe.Maybe"), `\_ValueType`, `NoReturn`, `NoReturn`], [`MaybeBasedN`](index.html#returns.interfaces.specific.maybe.MaybeBasedN "returns.interfaces.specific.maybe.MaybeBasedN")[`\_ValueType`, `None`, `NoReturn`]

Represents a result of a series of computations that can return `None`.

An alternative to using exceptions or constant `is None` checks.

`Maybe` is an abstract type and should not be instantiated directly.

Instead use `Some` and `Nothing`.

See also

* <https://github.com/gcanti/fp-ts/blob/master/docs/modules/Option.ts.md>

empty*: `ClassVar`[Maybe[Any]]* *= <Nothing>*[¶](#returns.maybe.Maybe.empty "Permalink to this definition")

Alias for Nothing

success\_type[¶](#returns.maybe.Maybe.success_type "Permalink to this definition")

Success type that is used to represent the successful computation.

Parameters:

**inner\_value** (`TypeVar`(`\_ValueType`, covariant=True)) – 

alias of [`Some`](#returns.maybe.Some "returns.maybe.Some")

failure\_type[¶](#returns.maybe.Maybe.failure_type "Permalink to this definition")

Failure type that is used to represent the failed computation.

Parameters:

**inner\_value** (`None`) – 

alias of `\_Nothing`

equals(*other*)[¶](#returns.maybe.Maybe.equals "Permalink to this definition")

Typesafe equality comparison with other Result objects.

Parameters:

* **self** ([`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_EqualType`, bound= [`Equable`](index.html#returns.interfaces.equable.Equable "returns.interfaces.equable.Equable")), `Any`, `Any`, `Any`]) –

* **other** ([`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_EqualType`, bound= [`Equable`](index.html#returns.interfaces.equable.Equable "returns.interfaces.equable.Equable")), `Any`, `Any`, `Any`]) –

Return type:

`bool`

map(*function*)[[source]](_modules/returns/maybe.html#Maybe.map)[¶](#returns.maybe.Maybe.map "Permalink to this definition")

Composes successful container with a pure function.

```

>>> from returns.maybe import Some, Nothing

>>> def mappable(string: str) -> str:

...      return string + 'b'

>>> assert Some('a').map(mappable) == Some('ab')

>>> assert Nothing.map(mappable) == Nothing

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `TypeVar`(`\_NewValueType`)]) – 

Return type:

[`Maybe`](#returns.maybe.Maybe "returns.maybe.Maybe")[`TypeVar`(`\_NewValueType`)]

apply(*function*)[[source]](_modules/returns/maybe.html#Maybe.apply)[¶](#returns.maybe.Maybe.apply "Permalink to this definition")

Calls a wrapped function in a container on this container.

```

>>> from returns.maybe import Some, Nothing

>>> def appliable(string: str) -> str:

...      return string + 'b'

>>> assert Some('a').apply(Some(appliable)) == Some('ab')

>>> assert Some('a').apply(Nothing) == Nothing

>>> assert Nothing.apply(Some(appliable)) == Nothing

>>> assert Nothing.apply(Nothing) == Nothing

```

Parameters:

**function** ([`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`Maybe`](#returns.maybe.Maybe "returns.maybe.Maybe"), `Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `TypeVar`(`\_NewValueType`)], `Any`, `Any`]) – 

Return type:

[`Maybe`](#returns.maybe.Maybe "returns.maybe.Maybe")[`TypeVar`(`\_NewValueType`)]

bind(*function*)[[source]](_modules/returns/maybe.html#Maybe.bind)[¶](#returns.maybe.Maybe.bind "Permalink to this definition")

Composes successful container with a function that returns a container.

```

>>> from returns.maybe import Nothing, Maybe, Some

>>> def bindable(string: str) -> Maybe[str]:

...      return Some(string + 'b')

>>> assert Some('a').bind(bindable) == Some('ab')

>>> assert Nothing.bind(bindable) == Nothing

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`Maybe`](#returns.maybe.Maybe "returns.maybe.Maybe"), `TypeVar`(`\_NewValueType`), `Any`, `Any`]]) – 

Return type:

[`Maybe`](#returns.maybe.Maybe "returns.maybe.Maybe")[`TypeVar`(`\_NewValueType`)]

bind\_optional(*function*)[[source]](_modules/returns/maybe.html#Maybe.bind_optional)[¶](#returns.maybe.Maybe.bind_optional "Permalink to this definition")

Binds a function returning an optional value over a container.

```

>>> from returns.maybe import Some, Nothing

>>> from typing import Optional

>>> def bindable(arg: str) -> Optional[int]:

...     return len(arg) if arg else None

>>> assert Some('a').bind\_optional(bindable) == Some(1)

>>> assert Some('').bind\_optional(bindable) == Nothing

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `Optional`[`TypeVar`(`\_NewValueType`)]]) – 

Return type:

[`Maybe`](#returns.maybe.Maybe "returns.maybe.Maybe")[`TypeVar`(`\_NewValueType`)]

lash(*function*)[[source]](_modules/returns/maybe.html#Maybe.lash)[¶](#returns.maybe.Maybe.lash "Permalink to this definition")

Composes failed container with a function that returns a container.

```

>>> from returns.maybe import Maybe, Some, Nothing

>>> def lashable(arg=None) -> Maybe[str]:

...      return Some('b')

>>> assert Some('a').lash(lashable) == Some('a')

>>> assert Nothing.lash(lashable) == Some('b')

```

We need this feature to make `Maybe` compatible

with different `Result` like operations.

Parameters:

**function** (`Callable`[[`Any`], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`Maybe`](#returns.maybe.Maybe "returns.maybe.Maybe"), `TypeVar`(`\_ValueType`, covariant=True), `Any`, `Any`]]) – 

Return type:

[`Maybe`](#returns.maybe.Maybe "returns.maybe.Maybe")[`TypeVar`(`\_ValueType`, covariant=True)]

*classmethod* do(*expr*)[[source]](_modules/returns/maybe.html#Maybe.do)[¶](#returns.maybe.Maybe.do "Permalink to this definition")

Allows working with unwrapped values of containers in a safe way.

```

>>> from returns.maybe import Maybe, Some, Nothing

>>> assert Maybe.do(

...     first + second

...     for first in Some(2)

...     for second in Some(3)

... ) == Some(5)

>>> assert Maybe.do(

...     first + second

...     for first in Some(2)

...     for second in Nothing

... ) == Nothing

```

See [Do Notation](index.html#do-notation) to learn more.

Parameters:

**expr** (`Generator`[`TypeVar`(`\_NewValueType`), `None`, `None`]) – 

Return type:

[`Maybe`](#returns.maybe.Maybe "returns.maybe.Maybe")[`TypeVar`(`\_NewValueType`)]

value\_or(*default\_value*)[[source]](_modules/returns/maybe.html#Maybe.value_or)[¶](#returns.maybe.Maybe.value_or "Permalink to this definition")

Get value from successful container or default value from failed one.

```

>>> from returns.maybe import Nothing, Some

>>> assert Some(0).value\_or(1) == 0

>>> assert Nothing.value\_or(1) == 1

```

Parameters:

**default\_value** (`TypeVar`(`\_NewValueType`)) – 

Return type:

`Union`[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_NewValueType`)]

or\_else\_call(*function*)[[source]](_modules/returns/maybe.html#Maybe.or_else_call)[¶](#returns.maybe.Maybe.or_else_call "Permalink to this definition")

Get value from successful container or default value from failed one.

Really close to [`value\_or()`](#returns.maybe.Maybe.value_or "returns.maybe.Maybe.value_or") but works with lazy values.

This method is unique to `Maybe` container, because other containers

do have `.alt` method.

But, `Maybe` does not have this method.

There’s nothing to `alt` in `Nothing`.

Instead, it has this method to execute

some function if called on a failed container:

```

>>> from returns.maybe import Some, Nothing

>>> assert Some(1).or\_else\_call(lambda: 2) == 1

>>> assert Nothing.or\_else\_call(lambda: 2) == 2

```

It might be useful to work with exceptions as well:

```

>>> def fallback() -> NoReturn:

...    raise ValueError('Nothing!')

>>> Nothing.or\_else\_call(fallback)

Traceback (most recent call last):

 ...

ValueError: Nothing!

```

Parameters:

**function** (`Callable`[[], `TypeVar`(`\_NewValueType`)]) – 

Return type:

`Union`[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_NewValueType`)]

unwrap()[[source]](_modules/returns/maybe.html#Maybe.unwrap)[¶](#returns.maybe.Maybe.unwrap "Permalink to this definition")

Get value from successful container or raise exception for failed one.

```

>>> from returns.maybe import Nothing, Some

>>> assert Some(1).unwrap() == 1

>>> Nothing.unwrap()

Traceback (most recent call last):

 ...

returns.primitives.exceptions.UnwrapFailedError

```

Return type:

`TypeVar`(`\_ValueType`, covariant=True)

failure()[[source]](_modules/returns/maybe.html#Maybe.failure)[¶](#returns.maybe.Maybe.failure "Permalink to this definition")

Get failed value from failed container or raise exception from success.

```

>>> from returns.maybe import Nothing, Some

>>> assert Nothing.failure() is None

>>> Some(1).failure()

Traceback (most recent call last):

 ...

returns.primitives.exceptions.UnwrapFailedError

```

Return type:

`None`

*classmethod* from\_value(*inner\_value*)[[source]](_modules/returns/maybe.html#Maybe.from_value)[¶](#returns.maybe.Maybe.from_value "Permalink to this definition")

Creates new instance of `Maybe` container based on a value.

```

>>> from returns.maybe import Maybe, Some

>>> assert Maybe.from\_value(1) == Some(1)

>>> assert Maybe.from\_value(None) == Some(None)

```

Parameters:

**inner\_value** (`TypeVar`(`\_NewValueType`)) – 

Return type:

[`Maybe`](#returns.maybe.Maybe "returns.maybe.Maybe")[`TypeVar`(`\_NewValueType`)]

*classmethod* from\_optional(*inner\_value*)[[source]](_modules/returns/maybe.html#Maybe.from_optional)[¶](#returns.maybe.Maybe.from_optional "Permalink to this definition")

Creates new instance of `Maybe` container based on an optional value.

```

>>> from returns.maybe import Maybe, Some, Nothing

>>> assert Maybe.from\_optional(1) == Some(1)

>>> assert Maybe.from\_optional(None) == Nothing

```

Parameters:

**inner\_value** (`Optional`[`TypeVar`(`\_NewValueType`)]) – 

Return type:

[`Maybe`](#returns.maybe.Maybe "returns.maybe.Maybe")[`TypeVar`(`\_NewValueType`)]

*final class* Some(*inner\_value*)[[source]](_modules/returns/maybe.html#Some)[¶](#returns.maybe.Some "Permalink to this definition")

Bases: [`Maybe`](#returns.maybe.Maybe "returns.maybe.Maybe")[`\_ValueType`]

Represents a calculation which has succeeded and contains the value.

Quite similar to `Success` type.

Parameters:

**inner\_value** (`TypeVar`(`\_ValueType`, covariant=True)) – 

bind(*function*)[[source]](_modules/returns/maybe.html#Some.bind)[¶](#returns.maybe.Some.bind "Permalink to this definition")

Binds current container to a function that returns container.

bind\_optional(*function*)[[source]](_modules/returns/maybe.html#Some.bind_optional)[¶](#returns.maybe.Some.bind_optional "Permalink to this definition")

Binds a function returning an optional value over a container.

unwrap()[[source]](_modules/returns/maybe.html#Some.unwrap)[¶](#returns.maybe.Some.unwrap "Permalink to this definition")

Returns inner value for successful container.

map(*function*)[[source]](_modules/returns/maybe.html#Some.map)[¶](#returns.maybe.Some.map "Permalink to this definition")

Composes current container with a pure function.

apply(*container*)[[source]](_modules/returns/maybe.html#Some.apply)[¶](#returns.maybe.Some.apply "Permalink to this definition")

Calls a wrapped function in a container on this container.

lash(*function*)[[source]](_modules/returns/maybe.html#Some.lash)[¶](#returns.maybe.Some.lash "Permalink to this definition")

Does nothing for `Some`.

value\_or(*default\_value*)[[source]](_modules/returns/maybe.html#Some.value_or)[¶](#returns.maybe.Some.value_or "Permalink to this definition")

Returns inner value for successful container.

or\_else\_call(*function*)[[source]](_modules/returns/maybe.html#Some.or_else_call)[¶](#returns.maybe.Some.or_else_call "Permalink to this definition")

Returns inner value for successful container.

failure()[[source]](_modules/returns/maybe.html#Some.failure)[¶](#returns.maybe.Some.failure "Permalink to this definition")

Raises exception for successful container.

Nothing*: [Maybe](index.html#returns.maybe.Maybe "returns.maybe.Maybe")[NoReturn]* *= <Nothing>*[¶](#returns.maybe.Nothing "Permalink to this definition")

Public unit value of protected `\_Nothing` type.

maybe(*function*)[[source]](_modules/returns/maybe.html#maybe)[¶](#returns.maybe.maybe "Permalink to this definition")

Decorator to convert `None`-returning function to `Maybe` container.

This decorator works with sync functions only. Example:

```

>>> from typing import Optional

>>> from returns.maybe import Nothing, Some, maybe

>>> @maybe

... def might\_be\_none(arg: int) -> Optional[int]:

...     if arg == 0:

...         return None

...     return 1 / arg

>>> assert might\_be\_none(0) == Nothing

>>> assert might\_be\_none(1) == Some(1.0)

```

Parameters:

**function** (`Callable`[[`ParamSpec`(`\_FuncParams`)], `Optional`[`TypeVar`(`\_ValueType`, covariant=True)]]) – 

Return type:

`Callable`[[`ParamSpec`(`\_FuncParams`)], [`Maybe`](#returns.maybe.Maybe "returns.maybe.Maybe")[`TypeVar`(`\_ValueType`, covariant=True)]]

Result[¶](#result "Permalink to this heading")

----------------------------------------------

Make sure to get familiar with [Railway oriented programming](index.html#railway).

`Result` is obviously a result of some series of computations.

It might succeed with some resulting value.

Or it might return an error with some extra details.

`Result` consist of two types: `Success` and `Failure`.

`Success` represents successful operation result

and `Failure` indicates that something has failed.

```

from returns.result import Result, Success, Failure

def find\_user(user\_id: int) -> Result['User', str]:

    user = User.objects.filter(id=user\_id)

    if user.exists():

        return Success(user[0])

    return Failure('User was not found')

user\_search\_result = find\_user(1)

# => Success(User{id: 1, ...})

user\_search\_result = find\_user(0)  # id 0 does not exist!

# => Failure('User was not found')

```

When is it useful?

When you do not want to use exceptions to break your execution scope.

Or when you do not want to use `None` to represent empty values,

since it will raise `TypeError` somewhere

and other `None` exception-friends.

### Composition[¶](#composition "Permalink to this heading")

Make sure to check out how to compose container with

`flow` or [pipe](index.html#pipe)!

Read more about them if you want to compose your containers easily.

### Pattern Matching[¶](#pattern-matching "Permalink to this heading")

`Result` values can be matched using the new feature of Python 3.10,

[Structural Pattern Matching](https://www.python.org/dev/peps/pep-0622/),

see the example below:

```

from returns.result import Failure, Success, safe

@safe

def div(first\_number: int, second\_number: int) -> int:

    return first\_number // second\_number

match div(1, 0):

    # Matches if the result stored inside `Success` is `10`

    case Success(10):

        print('Result is "10"')

    # Matches any `Success` instance and binds its value to the `value` variable

    case Success(value):

        print('Result is "{0}"'.format(value))

    # Matches if the result stored inside `Failure` is `ZeroDivisionError`

    case Failure(ZeroDivisionError()):

        print('"ZeroDivisionError" was raised')

    # Matches any `Failure` instance

    case Failure(\_):

        print('The division was a failure')

```

### Aliases[¶](#aliases "Permalink to this heading")

There are several useful alises for `Result` type with some common values:

* [`returns.result.ResultE`](#returns.result.ResultE "returns.result.ResultE") is an alias for `Result[... Exception]`,

just use it when you want to work with `Result` containers

that use exceptions as error type.

It is named `ResultE` because it is `ResultException`

and `ResultError` at the same time.

### Decorators[¶](#decorators "Permalink to this heading")

#### Limitations[¶](#limitations "Permalink to this heading")

Typing will only work correctly

if [our mypy plugin](index.html#mypy-plugins) is used.

This happens due to [mypy issue](https://github.com/python/mypy/issues/3157).

#### safe[¶](#safe "Permalink to this heading")

[`safe`](#returns.result.safe "returns.result.safe") is used to convert

regular functions that can throw exceptions to functions

that return [`Result`](#returns.result.Result "returns.result.Result") type.

Supports only regular functions.

If you need to mark `async` functions as `safe`,

use [`future\_safe`](index.html#returns.future.future_safe "returns.future.future_safe") instead.

```

>>> from returns.result import Success, safe

>>> @safe  # Will convert type to: Callable[[int], Result[float, Exception]]

... def divide(number: int) -> float:

...     return number / number

>>> assert divide(1) == Success(1.0)

>>> str(divide(0))

'<Failure: division by zero>'

```

If you want to safe handle only a set of exceptions:

```

>>> @safe(exceptions=(ZeroDivisionError,))  # Other exceptions will be raised

... def divide(number: int) -> float:

...     if number > 10:

...         raise ValueError('Too big')

...     return number / number

>>> assert divide(5) == Success(1.0)

>>> assert divide(0).failure()

>>> divide(15)

Traceback (most recent call last):

 ...

ValueError: Too big

```

#### attempt[¶](#attempt "Permalink to this heading")

Similar to [`safe`](#returns.result.safe "returns.result.safe") function but instead

of wrapping the exception error in a [`Failure`](#returns.result.Failure "returns.result.Failure") container it’ll wrap the

argument that lead to that exception.

```

>>> from returns.result import Failure, Success, attempt

>>> @attempt

... def divide\_itself(number: int) -> float:

...     return number / number

>>> assert divide\_itself(2) == Success(1.0)

>>> assert divide\_itself(0) == Failure(0)

```

Warning

This decorator works only with functions that has just one argument.

### FAQ[¶](#faq "Permalink to this heading")

#### How to create unit objects?[¶](#how-to-create-unit-objects "Permalink to this heading")

Use `Success` or `Failure`.

Alternatively [`returns.result.Result.from\_value()`](#returns.result.Result.from_value "returns.result.Result.from_value")

or [`returns.result.Result.from\_failure()`](#returns.result.Result.from_failure "returns.result.Result.from_failure").

It might be a good idea to use unit functions

together with the explicit annotation.

Python’s type system does not allow us to do much, so this is required:

```

>>> from returns.result import Result, Success

>>> def callback(arg: int) -> Result[float, int]:

...     return Success(float(arg))

>>> first: Result[int, int] = Success(1)

>>> assert first.bind(callback) == Success(1.0)

```

Otherwise `first` will have `Result[int, Any]` type.

Which is okay in some situations.

#### How to compose error types?[¶](#how-to-compose-error-types "Permalink to this heading")

You might want to sometimes use `unify` [Pointfree](index.html#pointfree) functions

instead of `.bind` to compose error types together.

While `.bind` enforces error type to stay the same,

`unify` is designed

to return a `Union` of a revious error type and a new one.

It gives an extra flexibility, but also provokes more thinking

and can be problematic in some cases.

Like so:

```

>>> from returns.result import Result, Success, Failure

>>> from returns.pointfree import unify

>>> def div(number: int) -> Result[float, ZeroDivisionError]:

...     if number:

...         return Success(1 / number)

...     return Failure(ZeroDivisionError('division by zero'))

>>> container: Result[int, ValueError] = Success(1)

>>> assert unify(div)(container) == Success(1.0)

>>> # => Revealed type is:

>>> # Result[float, Union[ValueError, ZeroDivisionError]]

```

So, that’s a way to go, if you need this composition.

#### map vs bind[¶](#map-vs-bind "Permalink to this heading")

We use the `map` method when we’re working with pure functions, a function

is pure if it doesn’t produce any side-effect (e.g. Exceptions). On the other

hand, we use the `bind` method if a function returns a `Result` instance

which translates its potential side-effect into a raw value.

See the example below:

```

>>> import json

>>> from typing import Dict

>>> from returns.result import Failure, Result, Success, safe

>>> # `cast\_to\_bool` doesn't produce any side-effect

>>> def cast\_to\_bool(arg: int) -> bool:

...     return bool(arg)

>>> # `parse\_json` can produce Exceptions, so we use the `safe` decorator

>>> # to prevent any kind of exceptions

>>> @safe

... def parse\_json(arg: str) -> Dict[str, str]:

...     return json.loads(arg)

>>> assert Success(1).map(cast\_to\_bool) == Success(True)

>>> assert Success('{"example": "example"}').bind(parse\_json) == Success({"example": "example"})

>>> assert Success('').bind(parse\_json).alt(str) == Failure('Expecting value: line 1 column 1 (char 0)')

```

#### How to check if your result is a success or failure?[¶](#how-to-check-if-your-result-is-a-success-or-failure "Permalink to this heading")

`Result` is a container and you can use [`returns.pipeline.is\_successful()`](index.html#returns.pipeline.is_successful "returns.pipeline.is_successful")

like so:

```

>>> from returns.result import Success, Failure

>>> from returns.pipeline import is\_successful

>>> assert is\_successful(Success(1)) is True

>>> assert is\_successful(Failure('text')) is False

```

### Further reading[¶](#further-reading "Permalink to this heading")

* [Railway Oriented Programming](https://fsharpforfunandprofit.com/rop/)

* [Recoverable Errors with Result in Rust](https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html)

* [Either overview in TypeScript](https://gcanti.github.io/fp-ts/modules/Either.ts.html)

### API Reference[¶](#api-reference "Permalink to this heading")

 classDiagram

 BaseContainer <|-- Result

 Result <|-- Failure

 Result <|-- Success

 ResultBasedN <|-- Result

 SupportsKindN <|-- Result

 

*class* Result(*inner\_value*)[[source]](_modules/returns/result.html#Result)[¶](#returns.result.Result "Permalink to this definition")

Bases: [`BaseContainer`](index.html#returns.primitives.container.BaseContainer "returns.primitives.container.BaseContainer"), [`SupportsKindN`](index.html#returns.primitives.hkt.SupportsKindN "returns.primitives.hkt.SupportsKindN")[[`Result`](#returns.result.Result "returns.result.Result"), `\_ValueType`, `\_ErrorType`, `NoReturn`], [`ResultBasedN`](index.html#returns.interfaces.specific.result.ResultBasedN "returns.interfaces.specific.result.ResultBasedN")[`\_ValueType`, `\_ErrorType`, `NoReturn`]

Base class for [`Failure`](#returns.result.Failure "returns.result.Failure") and [`Success`](#returns.result.Success "returns.result.Success").

[`Result`](#returns.result.Result "returns.result.Result") does not have a public constructor.

Use [`Success()`](#returns.result.Success "returns.result.Success") and [`Failure()`](#returns.result.Failure "returns.result.Failure") to construct the needed values.

See also

* <https://bit.ly/361qQhi>

* <https://hackernoon.com/the-throw-keyword-was-a-mistake-l9e532di>

success\_type[¶](#returns.result.Result.success_type "Permalink to this definition")

Success type that is used to represent the successful computation.

Parameters:

**inner\_value** (`TypeVar`(`\_ValueType`, covariant=True)) – 

alias of [`Success`](#returns.result.Success "returns.result.Success")

failure\_type[¶](#returns.result.Result.failure_type "Permalink to this definition")

Failure type that is used to represent the failed computation.

Parameters:

**inner\_value** (`TypeVar`(`\_ErrorType`, covariant=True)) – 

alias of [`Failure`](#returns.result.Failure "returns.result.Failure")

equals(*other*)[¶](#returns.result.Result.equals "Permalink to this definition")

Typesafe equality comparison with other Result objects.

Parameters:

* **self** ([`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_EqualType`, bound= [`Equable`](index.html#returns.interfaces.equable.Equable "returns.interfaces.equable.Equable")), `Any`, `Any`, `Any`]) –

* **other** ([`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_EqualType`, bound= [`Equable`](index.html#returns.interfaces.equable.Equable "returns.interfaces.equable.Equable")), `Any`, `Any`, `Any`]) –

Return type:

`bool`

*property* trace*: Optional[List[FrameInfo]]*[¶](#returns.result.Result.trace "Permalink to this definition")

Returns a list with stack trace when [`Failure()`](#returns.result.Failure "returns.result.Failure") was called.

swap()[[source]](_modules/returns/result.html#Result.swap)[¶](#returns.result.Result.swap "Permalink to this definition")

Swaps value and error types.

So, values become errors and errors become values.

It is useful when you have to work with errors a lot.

And since we have a lot of `.bind\_` related methods

and only a single `.lash` - it is easier to work with values.

```

>>> from returns.result import Success, Failure

>>> assert Success(1).swap() == Failure(1)

>>> assert Failure(1).swap() == Success(1)

```

Return type:

[`Result`](#returns.result.Result "returns.result.Result")[`TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_ValueType`, covariant=True)]

map(*function*)[[source]](_modules/returns/result.html#Result.map)[¶](#returns.result.Result.map "Permalink to this definition")

Composes successful container with a pure function.

```

>>> from returns.result import Failure, Success

>>> def mappable(string: str) -> str:

...      return string + 'b'

>>> assert Success('a').map(mappable) == Success('ab')

>>> assert Failure('a').map(mappable) == Failure('a')

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `TypeVar`(`\_NewValueType`)]) – 

Return type:

[`Result`](#returns.result.Result "returns.result.Result")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]

apply(*container*)[[source]](_modules/returns/result.html#Result.apply)[¶](#returns.result.Result.apply "Permalink to this definition")

Calls a wrapped function in a container on this container.

```

>>> from returns.result import Failure, Success

>>> def appliable(string: str) -> str:

...      return string + 'b'

>>> assert Success('a').apply(Success(appliable)) == Success('ab')

>>> assert Failure('a').apply(Success(appliable)) == Failure('a')

>>> assert Success('a').apply(Failure(1)) == Failure(1)

>>> assert Failure(1).apply(Failure(2)) == Failure(1)

```

Parameters:

**container** ([`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`Result`](#returns.result.Result "returns.result.Result"), `Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `TypeVar`(`\_NewValueType`)], `TypeVar`(`\_ErrorType`, covariant=True), `Any`]) – 

Return type:

[`Result`](#returns.result.Result "returns.result.Result")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]

bind(*function*)[[source]](_modules/returns/result.html#Result.bind)[¶](#returns.result.Result.bind "Permalink to this definition")

Composes successful container with a function that returns a container.

```

>>> from returns.result import Result, Success, Failure

>>> def bindable(arg: str) -> Result[str, str]:

...      if len(arg) > 1:

...          return Success(arg + 'b')

...      return Failure(arg + 'c')

>>> assert Success('aa').bind(bindable) == Success('aab')

>>> assert Success('a').bind(bindable) == Failure('ac')

>>> assert Failure('a').bind(bindable) == Failure('a')

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`Result`](#returns.result.Result "returns.result.Result"), `TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `Any`]]) – 

Return type:

[`Result`](#returns.result.Result "returns.result.Result")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]

bind\_result(*function*)[¶](#returns.result.Result.bind_result "Permalink to this definition")

Alias for bind\_result method, it is the same as bind here.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`Result`](#returns.result.Result "returns.result.Result"), `TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `Any`]]) – 

Return type:

[`Result`](#returns.result.Result "returns.result.Result")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]

alt(*function*)[[source]](_modules/returns/result.html#Result.alt)[¶](#returns.result.Result.alt "Permalink to this definition")

Composes failed container with a pure function to modify failure.

```

>>> from returns.result import Failure, Success

>>> def altable(arg: str) -> str:

...      return arg + 'b'

>>> assert Success('a').alt(altable) == Success('a')

>>> assert Failure('a').alt(altable) == Failure('ab')

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ErrorType`, covariant=True)], `TypeVar`(`\_NewErrorType`)]) – 

Return type:

[`Result`](#returns.result.Result "returns.result.Result")[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_NewErrorType`)]

lash(*function*)[[source]](_modules/returns/result.html#Result.lash)[¶](#returns.result.Result.lash "Permalink to this definition")

Composes failed container with a function that returns a container.

```

>>> from returns.result import Result, Success, Failure

>>> def lashable(arg: str) -> Result[str, str]:

...      if len(arg) > 1:

...          return Success(arg + 'b')

...      return Failure(arg + 'c')

>>> assert Success('a').lash(lashable) == Success('a')

>>> assert Failure('a').lash(lashable) == Failure('ac')

>>> assert Failure('aa').lash(lashable) == Success('aab')

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ErrorType`, covariant=True)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`Result`](#returns.result.Result "returns.result.Result"), `TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_NewErrorType`), `Any`]]) – 

Return type:

[`Result`](#returns.result.Result "returns.result.Result")[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_NewErrorType`)]

*classmethod* do(*expr*)[[source]](_modules/returns/result.html#Result.do)[¶](#returns.result.Result.do "Permalink to this definition")

Allows working with unwrapped values of containers in a safe way.

```

>>> from returns.result import Result, Failure, Success

>>> assert Result.do(

...     first + second

...     for first in Success(2)

...     for second in Success(3)

... ) == Success(5)

>>> assert Result.do(

...     first + second

...     for first in Failure('a')

...     for second in Success(3)

... ) == Failure('a')

```

See [Do Notation](index.html#do-notation) to learn more.

This feature requires our [mypy plugin](index.html#mypy-plugins).

Parameters:

**expr** (`Generator`[`TypeVar`(`\_NewValueType`), `None`, `None`]) – 

Return type:

[`Result`](#returns.result.Result "returns.result.Result")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]

value\_or(*default\_value*)[[source]](_modules/returns/result.html#Result.value_or)[¶](#returns.result.Result.value_or "Permalink to this definition")

Get value or default value.

```

>>> from returns.result import Failure, Success

>>> assert Success(1).value\_or(2) == 1

>>> assert Failure(1).value\_or(2) == 2

```

Parameters:

**default\_value** (`TypeVar`(`\_NewValueType`)) – 

Return type:

`Union`[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_NewValueType`)]

unwrap()[[source]](_modules/returns/result.html#Result.unwrap)[¶](#returns.result.Result.unwrap "Permalink to this definition")

Get value or raise exception.

```

>>> from returns.result import Failure, Success

>>> assert Success(1).unwrap() == 1

>>> Failure(1).unwrap()

Traceback (most recent call last):

 ...

returns.primitives.exceptions.UnwrapFailedError

```

Return type:

`TypeVar`(`\_ValueType`, covariant=True)

failure()[[source]](_modules/returns/result.html#Result.failure)[¶](#returns.result.Result.failure "Permalink to this definition")

Get failed value or raise exception.

```

>>> from returns.result import Failure, Success

>>> assert Failure(1).failure() == 1

>>> Success(1).failure()

Traceback (most recent call last):

 ...

returns.primitives.exceptions.UnwrapFailedError

```

Return type:

`TypeVar`(`\_ErrorType`, covariant=True)

*classmethod* from\_value(*inner\_value*)[[source]](_modules/returns/result.html#Result.from_value)[¶](#returns.result.Result.from_value "Permalink to this definition")

One more value to create success unit values.

It is useful as a united way to create a new value from any container.

```

>>> from returns.result import Result, Success

>>> assert Result.from\_value(1) == Success(1)

```

You can use this method or [`Success()`](#returns.result.Success "returns.result.Success"),

choose the most convenient for you.

Parameters:

**inner\_value** (`TypeVar`(`\_NewValueType`)) – 

Return type:

[`Result`](#returns.result.Result "returns.result.Result")[`TypeVar`(`\_NewValueType`), `Any`]

*classmethod* from\_failure(*inner\_value*)[[source]](_modules/returns/result.html#Result.from_failure)[¶](#returns.result.Result.from_failure "Permalink to this definition")

One more value to create failure unit values.

It is useful as a united way to create a new value from any container.

```

>>> from returns.result import Result, Failure

>>> assert Result.from\_failure(1) == Failure(1)

```

You can use this method or [`Failure()`](#returns.result.Failure "returns.result.Failure"),

choose the most convenient for you.

Parameters:

**inner\_value** (`TypeVar`(`\_NewErrorType`)) – 

Return type:

[`Result`](#returns.result.Result "returns.result.Result")[`Any`, `TypeVar`(`\_NewErrorType`)]

*classmethod* from\_result(*inner\_value*)[[source]](_modules/returns/result.html#Result.from_result)[¶](#returns.result.Result.from_result "Permalink to this definition")

Creates a new `Result` instance from existing `Result` instance.

```

>>> from returns.result import Result, Failure, Success

>>> assert Result.from\_result(Success(1)) == Success(1)

>>> assert Result.from\_result(Failure(1)) == Failure(1)

```

This is a part of

[`returns.interfaces.specific.result.ResultBasedN`](index.html#returns.interfaces.specific.result.ResultBasedN "returns.interfaces.specific.result.ResultBasedN") interface.

Parameters:

**inner\_value** ([`Result`](#returns.result.Result "returns.result.Result")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]) – 

Return type:

[`Result`](#returns.result.Result "returns.result.Result")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]

*final class* Failure(*inner\_value*)[[source]](_modules/returns/result.html#Failure)[¶](#returns.result.Failure "Permalink to this definition")

Bases: [`Result`](#returns.result.Result "returns.result.Result")[`Any`, `\_ErrorType`]

Represents a calculation which has failed.

It should contain an error code or message.

Parameters:

**inner\_value** (`TypeVar`(`\_ErrorType`, covariant=True)) – 

alt(*function*)[[source]](_modules/returns/result.html#Failure.alt)[¶](#returns.result.Failure.alt "Permalink to this definition")

Composes failed container with a pure function to modify failure.

map(*function*)[[source]](_modules/returns/result.html#Failure.map)[¶](#returns.result.Failure.map "Permalink to this definition")

Does nothing for `Failure`.

bind(*function*)[[source]](_modules/returns/result.html#Failure.bind)[¶](#returns.result.Failure.bind "Permalink to this definition")

Does nothing for `Failure`.

bind\_result(*function*)[¶](#returns.result.Failure.bind_result "Permalink to this definition")

Alias for bind method. Part of the ResultBasedN interface.

lash(*function*)[[source]](_modules/returns/result.html#Failure.lash)[¶](#returns.result.Failure.lash "Permalink to this definition")

Composes this container with a function returning container.

apply(*container*)[[source]](_modules/returns/result.html#Failure.apply)[¶](#returns.result.Failure.apply "Permalink to this definition")

Does nothing for `Failure`.

value\_or(*default\_value*)[[source]](_modules/returns/result.html#Failure.value_or)[¶](#returns.result.Failure.value_or "Permalink to this definition")

Returns default value for failed container.

swap()[[source]](_modules/returns/result.html#Failure.swap)[¶](#returns.result.Failure.swap "Permalink to this definition")

Failures swap to [`Success`](#returns.result.Success "returns.result.Success").

unwrap()[[source]](_modules/returns/result.html#Failure.unwrap)[¶](#returns.result.Failure.unwrap "Permalink to this definition")

Raises an exception, since it does not have a value inside.

Return type:

`NoReturn`

failure()[[source]](_modules/returns/result.html#Failure.failure)[¶](#returns.result.Failure.failure "Permalink to this definition")

Returns failed value.

Return type:

`TypeVar`(`\_ErrorType`, covariant=True)

*final class* Success(*inner\_value*)[[source]](_modules/returns/result.html#Success)[¶](#returns.result.Success "Permalink to this definition")

Bases: [`Result`](#returns.result.Result "returns.result.Result")[`\_ValueType`, `Any`]

Represents a calculation which has succeeded and contains the result.

Contains the computation value.

Parameters:

**inner\_value** (`TypeVar`(`\_ValueType`, covariant=True)) – 

alt(*function*)[[source]](_modules/returns/result.html#Success.alt)[¶](#returns.result.Success.alt "Permalink to this definition")

Does nothing for `Success`.

map(*function*)[[source]](_modules/returns/result.html#Success.map)[¶](#returns.result.Success.map "Permalink to this definition")

Composes current container with a pure function.

bind(*function*)[[source]](_modules/returns/result.html#Success.bind)[¶](#returns.result.Success.bind "Permalink to this definition")

Binds current container to a function that returns container.

bind\_result(*function*)[¶](#returns.result.Success.bind_result "Permalink to this definition")

Alias for bind method. Part of the ResultBasedN interface.

lash(*function*)[[source]](_modules/returns/result.html#Success.lash)[¶](#returns.result.Success.lash "Permalink to this definition")

Does nothing for `Success`.

apply(*container*)[[source]](_modules/returns/result.html#Success.apply)[¶](#returns.result.Success.apply "Permalink to this definition")

Calls a wrapped function in a container on this container.

value\_or(*default\_value*)[[source]](_modules/returns/result.html#Success.value_or)[¶](#returns.result.Success.value_or "Permalink to this definition")

Returns the value for successful container.

swap()[[source]](_modules/returns/result.html#Success.swap)[¶](#returns.result.Success.swap "Permalink to this definition")

Successes swap to [`Failure`](#returns.result.Failure "returns.result.Failure").

unwrap()[[source]](_modules/returns/result.html#Success.unwrap)[¶](#returns.result.Success.unwrap "Permalink to this definition")

Returns the unwrapped value from successful container.

Return type:

`TypeVar`(`\_ValueType`, covariant=True)

failure()[[source]](_modules/returns/result.html#Success.failure)[¶](#returns.result.Success.failure "Permalink to this definition")

Raises an exception for successful container.

Return type:

`NoReturn`

ResultE[¶](#returns.result.ResultE "Permalink to this definition")

Alias for a popular case when `Result` has `Exception` as error type.

alias of [`Result`](#returns.result.Result "returns.result.Result")[`\_ValueType`, `Exception`]

safe(*function=None*, *exceptions=None*)[[source]](_modules/returns/result.html#safe)[¶](#returns.result.safe "Permalink to this definition")

Decorator to convert exception-throwing function to `Result` container.

Should be used with care, since it only catches `Exception` subclasses.

It does not catch `BaseException` subclasses.

If you need to mark `async` function as `safe`,

use [`returns.future.future\_safe()`](index.html#returns.future.future_safe "returns.future.future_safe") instead.

This decorator only works with sync functions. Example:

```

>>> from returns.result import Result, Success, safe

>>> @safe

... def might\_raise(arg: int) -> float:

...     return 1 / arg

>>> assert might\_raise(1) == Success(1.0)

>>> assert isinstance(might\_raise(0), Result.failure\_type)

```

You can also use it with explicit exception types as the first argument:

```

>>> from returns.result import Result, Success, safe

>>> @safe(exceptions=(ZeroDivisionError,))

... def might\_raise(arg: int) -> float:

...     return 1 / arg

>>> assert might\_raise(1) == Success(1.0)

>>> assert isinstance(might\_raise(0), Result.failure\_type)

```

In this case, only exceptions that are explicitly

listed are going to be caught.

Similar to [`returns.io.impure\_safe()`](index.html#returns.io.impure_safe "returns.io.impure_safe")

and [`returns.future.future\_safe()`](index.html#returns.future.future_safe "returns.future.future_safe") decorators.

Parameters:

* **function** (`Optional`[`Callable`[[`ParamSpec`(`\_FuncParams`)], `TypeVar`(`\_ValueType`, covariant=True)]]) –

* **exceptions** (`Optional`[`Tuple`[`Type`[`Exception`], `...`]]) –

Return type:

`Union`[`Callable`[[`ParamSpec`(`\_FuncParams`)], [`Result`](#returns.result.Result "returns.result.Result")[`TypeVar`(`\_ValueType`, covariant=True), `Exception`]], `Callable`[[`Callable`[[`ParamSpec`(`\_FuncParams`)], `TypeVar`(`\_ValueType`, covariant=True)]], `Callable`[[`ParamSpec`(`\_FuncParams`)], [`Result`](#returns.result.Result "returns.result.Result")[`TypeVar`(`\_ValueType`, covariant=True), `Exception`]]]]

attempt(*func*)[[source]](_modules/returns/result.html#attempt)[¶](#returns.result.attempt "Permalink to this definition")

Decorator to convert exception-throwing function to `Result` container.

It’s very similar with [`returns.result.safe()`](#returns.result.safe "returns.result.safe"), the difference is when

an exception is raised it won’t wrap that given exception into a Failure,

it’ll wrap the argument that lead to the exception.

```

>>> import json

>>> from typing import Dict, Any

>>> from returns.result import Failure, Success, attempt

>>> @attempt

... def parse\_json(string: str) -> Dict[str, Any]:

...     return json.loads(string)

>>> assert parse\_json('{"key": "value"}') == Success({'key': 'value'})

>>> assert parse\_json('incorrect input') == Failure('incorrect input')

```

Parameters:

**func** (`Callable`[[`TypeVar`(`\_FirstType`)], `TypeVar`(`\_NewValueType`)]) – 

Return type:

`Callable`[[`TypeVar`(`\_FirstType`)], [`Result`](#returns.result.Result "returns.result.Result")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_FirstType`)]]

IO[¶](#io "Permalink to this heading")

--------------------------------------

Mathematicians dream in pure functions.

Each of them only relies on its arguments

and always produces the same result for the same input.

That’s not how a useful program works.

We need to rely on the environment and we need to do side effects.

Furthermore, there are several types of `IO` in our programs:

* Some `IO` never fails, like:

getting current date and time, random number, or OS name

* Some `IO` might fail, like:

sending network requests, accessing filesystem, or database

There’s a solution.

### IO container[¶](#io-container "Permalink to this heading")

Once you have an `IO` operation you can mark it appropriately.

We can use a simple class [`returns.io.IO`](#returns.io.IO "returns.io.IO")

to mark impure parts of the program that do not fail.

```

>>> import random

>>> from returns.io import IO

>>> def get\_random\_number() -> IO[int]:

...     return IO(random.randint(1, 10))

...

>>> assert isinstance(get\_random\_number(), IO)

```

And later we can work inside this `IO` context

and do not break into our pure part of the program:

```

>>> assert get\_random\_number().map(lambda number: number / number) == IO(1.0)

```

And it infects all other functions that call it.

```

>>> def modify\_number(number: int) -> IO[float]:

...     return get\_random\_number().map(lambda rnd: number / rnd)

...

>>> assert isinstance(modify\_number(1), IO)

```

It is good enough to indicate

that you are aware of side effects of the function.

### IOResult[¶](#ioresult "Permalink to this heading")

On the other hand, we can have `IO` parts of the program that do fail.

Imagine we have this beautiful pure function:

```

def can\_book\_seats(

    number\_of\_seats: int,

    reservation: 'Reservation',

) -> bool:

    return reservation.capacity >= number\_of\_seats + reservation.booked

```

What’s good about it? We can test it easily.

Even without setting up any testing framework,

simple [doctests](https://docs.python.org/3/library/doctest.html)

will be enough.

This code is **beautiful**, because it is **simple**.

We can later use its result to process the result of the booking request:

```

def process\_booking\_result(is\_successful: bool) -> 'ProcessID':

    ...

process\_booking\_result(is\_successful)  # works just fine!

```

At this point we don’t have `IO` in our program.

#### Impure functions[¶](#impure-functions "Permalink to this heading")

But, imagine that our requirements had changed.

And now we have to grab the number of already booked tickets

from some other microservice and fetch the maximum capacity from the database:

```

import requests

import db

def can\_book\_seats(

    number\_of\_seats: int,

    place\_id: int,

) -> bool:

    capacity = db.get\_place\_capacity(place\_id)  # sql query

    booked = requests('https://partner.com/api').json()['booked']  # http req

    return capacity >= number\_of\_seats + booked

```

Now testing this code will become a nightmare!

It will require to setup:

* real database and tables

* fixture data

* `requests` mocks for different outcomes

* and the whole Universe!

Our complexity has sky-rocketed!

And the most annoying part is that all other functions

that call `can\_book\_seats` now also have to do the same setup.

It seams like `IO` is indelible mark (some people also call it “effect”).

And at some point it time we will start to mix pure and impure code together.

Let’s not forget that all of these operations can fail too!

#### Separating two worlds[¶](#separating-two-worlds "Permalink to this heading")

Well, `IO` mark is indeed indelible and should be respected.

And then impurity becomes explicit:

```

import requests

import db

from returns.io import IOResultE

def can\_book\_seats(

    number\_of\_seats: int,

    place\_id: int,

) -> IOResultE[bool]:

    ...

```

Now this function returns `IOResultE[bool]` instead of a regular `bool`.

It means, that it cannot be used where regular `bool` can be:

```

def process\_booking\_result(is\_successful: bool) -> 'ProcessID':

    ...

is\_successful: IOResultE[bool] = can\_book\_seats(number\_of\_seats, place\_id)

process\_booking\_result(is\_successful)  # Boom!

# => Argument 1 has incompatible type "IOResultE[bool]"; expected "bool"

```

See? It is now impossible for a pure function to use `IOResultE[bool]`.

It is impossible to unwrap or get a raw value from this container.

Once it is marked as `IO` it will never return to the pure state

(well, there’s a hack actually:

[`unsafe\_perform\_io`](#returns.unsafe.unsafe_perform_io "returns.unsafe.unsafe_perform_io")).

Now we have to work inside the `IO` context:

```

message\_id: IOResultE['ProcessID'] = can\_book\_seats(

    number\_of\_seats,

    place\_id,

).map(

    process\_booking\_result,

)

```

Or it can be annotated to work with impure results:

```

def process\_booking\_result(

    is\_successful: IOResultE[bool],

) -> IOResultE['ProcessID']:

    ...

is\_successful: IOResult[bool] = can\_book\_seats(number\_of\_seats, place\_id)

process\_booking\_result(is\_successful)  # Works!

```

Now, all our impurity is explicit.

We can track it, we can fight it, we can design it better.

By saying that, it is assumed that

you have a functional core and imperative shell.

#### Lifting[¶](#lifting "Permalink to this heading")

You can also lift regular functions into one

that works with `IO` or `IOResult` on both ends.

It really helps you with the composition!

```

>>> from returns.io import IO

>>> from returns.pointfree import map\_

>>> def regular\_function(arg: int) -> float:

...     return arg / 2  # not an `IO` operation

>>> container = IO(1)

>>> # When we need to compose `regular\_function` with `IO`,

>>> # we have two ways of doing it:

>>> io = container.map(regular\_function)

>>> assert io == IO(0.5)

>>> # or, it is the same as:

>>> io = map\_(regular\_function)(container)

>>> assert io == IO(0.5)

```

`IOResult` can lift both regular functions and ones that return `Result`:

```

>>> from returns.io import IOResult, IOSuccess

>>> from returns.pointfree import map\_

>>> def regular\_function(arg: int) -> float:

...     return arg / 2  # not an `IO` operation

>>> container: IOResult[int, str] = IOSuccess(1)

>>> # When we need to compose `regular\_function` with `IOResult`,

>>> # we have two ways of doing it:

>>> io = container.map(regular\_function)

>>> assert io == IOSuccess(0.5)

>>> # or, it is the same as:

>>> io = map\_(regular\_function)(container)

>>> assert io == IOSuccess(0.5)

```

And `Result` based functions:

```

>>> from returns.io import IOResult, IOSuccess

>>> from returns.result import Result, Success, Failure

>>> from returns.pointfree import bind\_result

>>> def regular\_function(arg: int) -> Result[float, str]:

...     if arg > 0:

...         return Success(arg / 2)

...     return Failure('zero')

>>> assert bind\_result(regular\_function)(

...     IOSuccess(1),

... ) == IOResult.from\_result(regular\_function(1))

```

Lifting is useful when using [`returns.pipeline.pipe()`](index.html#returns.pipeline.pipe "returns.pipeline.pipe")

and other different declarative tools.

### Pattern Matching[¶](#pattern-matching "Permalink to this heading")

`IOResult` values can be matched using the new feature of Python 3.10,

[Structural Pattern Matching](https://www.python.org/dev/peps/pep-0622/),

see the example below:

```

from returns.io import IOFailure, IOResult, IOSuccess

from returns.result import Success

container: IOResult[int, str] = IOSuccess(42)

match container:

    # Matches if the result stored inside `IOSuccess` is `42`

    # We need to use `Success` until the custom matching protocol

    # is released. For more information, please visit:

    # https://www.python.org/dev/peps/pep-0622/#custom-matching-protocol

    case IOSuccess(Success(42)):

        print('Result is "42"')

    # Matches any `IOSuccess` instance

    # and binds its value to the `value` variable

    case IOSuccess(value):

        print('Result is "{0}"'.format(value))

    # Matches any `IOFailure` instance

    case IOFailure(\_):

        print('A failure was occurred')

```

### Aliases[¶](#aliases "Permalink to this heading")

There are several useful alises for `IOResult` type with some common values:

* [`returns.io.IOResultE`](#returns.io.IOResultE "returns.io.IOResultE") is an alias for `IOResult[... Exception]`,

just use it when you want to work with `IOResult` containers

that use exceptions as error type.

It is named `IOResultE` because it is `IOResultException`

and `IOResultError` at the same time.

### Decorators[¶](#decorators "Permalink to this heading")

#### Limitations[¶](#limitations "Permalink to this heading")

Typing will only work correctly

if [our mypy plugin](index.html#mypy-plugins) is used.

This happens due to [mypy issue](https://github.com/python/mypy/issues/3157).

#### impure[¶](#impure "Permalink to this heading")

We also have this handy decorator to help

you with the existing impure things in Python:

```

from returns.io import impure

name: IO[str] = impure(input)('What is your name?')

```

You can also decorate your own functions

with `@impure` for better readability and clearness:

```

import random

from returns.io import impure

@impure

def get\_user() -> 'User':

    return random.randint(1, 5)

```

#### impure\_safe[¶](#impure-safe "Permalink to this heading")

Similar to `impure` and `safe` decorators.

Once applied, it transforms the return type to be `IOResultE`:

```

from returns.io import IOResultE, impure\_safe

@impure\_safe

def http\_get(path: str) -> 'Response':

    return requests.get(path)

container: IOResultE['Response'] = http\_get('/home')

```

Use for impure operations that might fail.

### Helpers[¶](#helpers "Permalink to this heading")

Don’t forget to check out [Converters](index.html#converters).

#### unsafe\_perform\_io[¶](#unsafe-perform-io "Permalink to this heading")

Sometimes you really need to get the raw value from `IO` container.

For example:

```

def index\_view(request, user\_id):

    user: IO[User] = get\_user(user\_id)

    return render('index.html', {'user': user})  # ???

```

In this case your web-framework will not render your user correctly.

Since it does not expect it to be wrapped inside `IO` containers.

And we obviously cannot `map` or `bind` this function.

What to do? Use [`unsafe\_perform\_io`](#returns.unsafe.unsafe_perform_io "returns.unsafe.unsafe_perform_io"):

```

from returns.unsafe import unsafe\_perform\_io

def index\_view(request, user\_id):

    user: IO[User] = get\_user(user\_id)

    return render('index.html', {'user': unsafe\_perform\_io(user)})  # Ok

```

We need it as an escape and compatibility mechanism for our imperative shell.

In other words:

```

>>> from returns.unsafe import unsafe\_perform\_io

>>> from returns.io import IO

>>> assert unsafe\_perform\_io(IO('abc')) == 'abc'

```

It is recommended

to use [import-linter](https://github.com/seddonym/import-linter)

to restrict imports from `returns.unsafe` expect the top-level modules.

Inspired by Haskell’s

[unsafePerformIO](https://hackage.haskell.org/package/base-4.12.0.0/docs/System-IO-Unsafe.html#v:unsafePerformIO)

### FAQ[¶](#faq "Permalink to this heading")

#### Why aren’t IO lazy?[¶](#why-aren-t-io-lazy "Permalink to this heading")

Please, note that our `IO` implementation is not lazy by design.

This way when you mark something as `@impure` it will work as previously.

The only thing that changes is the return type.

Instead we offer to use [unsafe\_perform\_io](#unsafe-perform-io)

to work with `IO` and simulate laziness.

But, you can always make your `IO` lazy:

```

>>> from returns.io import IO

>>> lazy = lambda: IO(1)

>>> assert lazy() == IO(1)

```

We have decided that it would be better and more familiar for Python devs.

#### What is the difference between IO[T] and T?[¶](#what-is-the-difference-between-io-t-and-t "Permalink to this heading")

What kind of input parameter should

my function accept `IO[T]` or simple `T`?

It really depends on your domain / context.

If the value is pure, than use raw unwrapped values.

If the value is fetched, input, received, selected,

than use `IO` or `IOResult` container:

first one for operations that never fail,

second one for operations that might fail.

Most web applications are just fully covered with `IO`.

#### Why can’t we use IO[Result] instead of IOResult?[¶](#why-can-t-we-use-io-result-instead-of-ioresult "Permalink to this heading")

We actually can! But, it is harder to write.

And `IOResult` is actually the very same thing as `IO[Result]`,

but has nicer API:

```

x: IO[Result[int, str]]

x.map(lambda io: io.map(lambda number: number + 1))

# Is the same as:

y: IOResult[int, str]

y.map(lambda number: number + 1)

```

The second one looks better, doesn’t it?

#### How to create unit objects for IOResult?[¶](#how-to-create-unit-objects-for-ioresult "Permalink to this heading")

*TLDR*: you need to use `IOSuccess` and `IOFailure` functions

or `IOResult.from\_value` and `IOResult.from\_failure` methods:

```

>>> from returns.io import IOResult, IOSuccess, IOFailure

>>> first: IOResult[int, str] = IOSuccess(1)

>>> second: IOResult[float, int] = IOFailure(1)

>>> assert IOResult.from\_value(1) == IOSuccess(1)

>>> assert IOResult.from\_failure(2) == IOFailure(2)

```

You can also annotate your variables properly.

Otherwise, `mypy` will treat `IOSuccess(1)` as `IOSuccess[int, Any]`.

You can narrow the type in advance.

See [How to create unit objects?](index.html#result-units) for more details.

### Further reading[¶](#further-reading "Permalink to this heading")

* [Functional core, imperative shell](https://www.destroyallsoftware.com/screencasts/catalog/functional-core-imperative-shell)

* [Functional architecture is Ports and Adapters](https://blog.ploeh.dk/2016/03/18/functional-architecture-is-ports-and-adapters/)

* [IO effect in Scala](https://typelevel.org/cats-effect/datatypes/io.html)

* [Getting started with fp-ts: IO](https://dev.to/gcanti/getting-started-with-fp-ts-io-36p6)

* [IOEither](https://github.com/gcanti/fp-ts/blob/master/docs/modules/IOEither.ts.md)

* [Effect Tracking Is Commercially Worthless](https://degoes.net/articles/no-effect-tracking)

### API Reference[¶](#api-reference "Permalink to this heading")

 classDiagram

 BaseContainer <|-- IO

 BaseContainer <|-- IOResult

 IOLikeN <|-- IO

 IOResult <|-- IOFailure

 IOResult <|-- IOSuccess

 IOResultBasedN <|-- IOResult

 SupportsKindN <|-- IO

 SupportsKindN <|-- IOResult

 

*class* IO(*inner\_value*)[[source]](_modules/returns/io.html#IO)[¶](#returns.io.IO "Permalink to this definition")

Bases: [`BaseContainer`](index.html#returns.primitives.container.BaseContainer "returns.primitives.container.BaseContainer"), [`SupportsKindN`](index.html#returns.primitives.hkt.SupportsKindN "returns.primitives.hkt.SupportsKindN")[[`IO`](#returns.io.IO "returns.io.IO"), `\_ValueType`, `NoReturn`, `NoReturn`], [`IOLikeN`](index.html#returns.interfaces.specific.io.IOLikeN "returns.interfaces.specific.io.IOLikeN")[`\_ValueType`, `NoReturn`, `NoReturn`]

Explicit container for impure function results.

We also sometimes call it “marker” since once it is marked,

it cannot be ever unmarked.

There’s no way to directly get its internal value.

Note that `IO` represents a computation that never fails.

Examples of such computations are:

* read / write to localStorage

* get the current time

* write to the console

* get a random number

Use `IOResult[...]` for operations that might fail.

Like DB access or network operations.

See also

* <https://dev.to/gcanti/getting-started-with-fp-ts-io-36p6>

* <https://gist.github.com/chris-taylor/4745921>

Parameters:

**inner\_value** (`TypeVar`(`\_ValueType`, covariant=True)) – 

equals(*other*)[¶](#returns.io.IO.equals "Permalink to this definition")

Typesafe equality comparison with other Result objects.

Parameters:

* **self** ([`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_EqualType`, bound= [`Equable`](index.html#returns.interfaces.equable.Equable "returns.interfaces.equable.Equable")), `Any`, `Any`, `Any`]) –

* **other** ([`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_EqualType`, bound= [`Equable`](index.html#returns.interfaces.equable.Equable "returns.interfaces.equable.Equable")), `Any`, `Any`, `Any`]) –

Return type:

`bool`

map(*function*)[[source]](_modules/returns/io.html#IO.map)[¶](#returns.io.IO.map "Permalink to this definition")

Applies function to the inner value.

Applies ‘function’ to the contents of the IO instance

and returns a new IO object containing the result.

‘function’ should accept a single “normal” (non-container) argument

and return a non-container result.

```

>>> def mappable(string: str) -> str:

...      return string + 'b'

>>> assert IO('a').map(mappable) == IO('ab')

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `TypeVar`(`\_NewValueType`)]) – 

Return type:

[`IO`](#returns.io.IO "returns.io.IO")[`TypeVar`(`\_NewValueType`)]

apply(*container*)[[source]](_modules/returns/io.html#IO.apply)[¶](#returns.io.IO.apply "Permalink to this definition")

Calls a wrapped function in a container on this container.

```

>>> from returns.io import IO

>>> assert IO('a').apply(IO(lambda inner: inner + 'b')) == IO('ab')

```

Or more complex example that shows how we can work

with regular functions and multiple `IO` arguments:

```

>>> from returns.curry import curry

>>> @curry

... def appliable(first: str, second: str) -> str:

...      return first + second

>>> assert IO('b').apply(IO('a').apply(IO(appliable))) == IO('ab')

```

Parameters:

**container** ([`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`IO`](#returns.io.IO "returns.io.IO"), `Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `TypeVar`(`\_NewValueType`)], `Any`, `Any`]) – 

Return type:

[`IO`](#returns.io.IO "returns.io.IO")[`TypeVar`(`\_NewValueType`)]

bind(*function*)[[source]](_modules/returns/io.html#IO.bind)[¶](#returns.io.IO.bind "Permalink to this definition")

Applies ‘function’ to the result of a previous calculation.

‘function’ should accept a single “normal” (non-container) argument

and return `IO` type object.

```

>>> def bindable(string: str) -> IO[str]:

...      return IO(string + 'b')

>>> assert IO('a').bind(bindable) == IO('ab')

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`IO`](#returns.io.IO "returns.io.IO"), `TypeVar`(`\_NewValueType`), `Any`, `Any`]]) – 

Return type:

[`IO`](#returns.io.IO "returns.io.IO")[`TypeVar`(`\_NewValueType`)]

bind\_io(*function*)[¶](#returns.io.IO.bind_io "Permalink to this definition")

Alias for bind method. Part of the IOLikeN interface.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`IO`](#returns.io.IO "returns.io.IO"), `TypeVar`(`\_NewValueType`), `Any`, `Any`]]) – 

Return type:

[`IO`](#returns.io.IO "returns.io.IO")[`TypeVar`(`\_NewValueType`)]

*classmethod* do(*expr*)[[source]](_modules/returns/io.html#IO.do)[¶](#returns.io.IO.do "Permalink to this definition")

Allows working with unwrapped values of containers in a safe way.

```

>>> from returns.io import IO

>>> assert IO.do(

...     first + second

...     for first in IO(2)

...     for second in IO(3)

... ) == IO(5)

```

See [Do Notation](index.html#do-notation) to learn more.

Parameters:

**expr** (`Generator`[`TypeVar`(`\_NewValueType`), `None`, `None`]) – 

Return type:

[`IO`](#returns.io.IO "returns.io.IO")[`TypeVar`(`\_NewValueType`)]

*classmethod* from\_value(*inner\_value*)[[source]](_modules/returns/io.html#IO.from_value)[¶](#returns.io.IO.from_value "Permalink to this definition")

Unit function to construct new `IO` values.

Is the same as regular constructor:

```

>>> from returns.io import IO

>>> assert IO(1) == IO.from\_value(1)

```

Part of the [`returns.interfaces.applicative.ApplicativeN`](index.html#returns.interfaces.applicative.ApplicativeN "returns.interfaces.applicative.ApplicativeN")

interface.

Parameters:

**inner\_value** (`TypeVar`(`\_NewValueType`)) – 

Return type:

[`IO`](#returns.io.IO "returns.io.IO")[`TypeVar`(`\_NewValueType`)]

*classmethod* from\_io(*inner\_value*)[[source]](_modules/returns/io.html#IO.from_io)[¶](#returns.io.IO.from_io "Permalink to this definition")

Unit function to construct new `IO` values from existing `IO`.

```

>>> from returns.io import IO

>>> assert IO(1) == IO.from\_io(IO(1))

```

Part of the `returns.interfaces.specific.IO.IOLikeN` interface.

Parameters:

**inner\_value** ([`IO`](#returns.io.IO "returns.io.IO")[`TypeVar`(`\_NewValueType`)]) – 

Return type:

[`IO`](#returns.io.IO "returns.io.IO")[`TypeVar`(`\_NewValueType`)]

*classmethod* from\_ioresult(*inner\_value*)[[source]](_modules/returns/io.html#IO.from_ioresult)[¶](#returns.io.IO.from_ioresult "Permalink to this definition")

Converts `IOResult[a, b]` back to `IO[Result[a, b]]`.

Can be really helpful for composition.

```

>>> from returns.io import IO, IOSuccess

>>> from returns.result import Success

>>> assert IO.from\_ioresult(IOSuccess(1)) == IO(Success(1))

```

Is the reverse of [`returns.io.IOResult.from\_typecast()`](#returns.io.IOResult.from_typecast "returns.io.IOResult.from_typecast").

Parameters:

**inner\_value** ([`IOResult`](#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]) – 

Return type:

[`IO`](#returns.io.IO "returns.io.IO")[[`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]]

impure(*function*)[[source]](_modules/returns/io.html#impure)[¶](#returns.io.impure "Permalink to this definition")

Decorator to mark function that it returns [`IO`](#returns.io.IO "returns.io.IO") container.

If you need to mark `async` function as impure,

use [`returns.future.future()`](index.html#returns.future.future "returns.future.future") instead.

This decorator only works with sync functions. Example:

```

>>> from returns.io import IO, impure

>>> @impure

... def function(arg: int) -> int:

...     return arg + 1  # this action is pure, just an example

...

>>> assert function(1) == IO(2)

```

Parameters:

**function** (`Callable`[[`ParamSpec`(`\_FuncParams`)], `TypeVar`(`\_NewValueType`)]) – 

Return type:

`Callable`[[`ParamSpec`(`\_FuncParams`)], [`IO`](#returns.io.IO "returns.io.IO")[`TypeVar`(`\_NewValueType`)]]

*class* IOResult(*inner\_value*)[[source]](_modules/returns/io.html#IOResult)[¶](#returns.io.IOResult "Permalink to this definition")

Bases: [`BaseContainer`](index.html#returns.primitives.container.BaseContainer "returns.primitives.container.BaseContainer"), [`SupportsKindN`](index.html#returns.primitives.hkt.SupportsKindN "returns.primitives.hkt.SupportsKindN")[[`IOResult`](#returns.io.IOResult "returns.io.IOResult"), `\_ValueType`, `\_ErrorType`, `NoReturn`], [`IOResultBasedN`](index.html#returns.interfaces.specific.ioresult.IOResultBasedN "returns.interfaces.specific.ioresult.IOResultBasedN")[`\_ValueType`, `\_ErrorType`, `NoReturn`]

Explicit container for impure function results that might fail.

Definition

This type is similar to [`returns.result.Result`](index.html#returns.result.Result "returns.result.Result").

This basically a more useful version of `IO[Result[a, b]]`.

Use this type for `IO` computations that might fail.

Examples of `IO` computations that might fail are:

* access database

* access network

* access filesystem

Use [`IO`](#returns.io.IO "returns.io.IO") for operations that do `IO` but do not fail.

Note, that even methods like `unwrap`()`

and [`value\_or()`](#returns.io.IOResult.value_or "returns.io.IOResult.value_or") return values wrapped in `IO`.

`IOResult` is a complex compound value that consists of:

* raw value

* `Result`

* `IO`

This is why it has so many helper and factory methods:

* You can construct `IOResult` from raw values

with [`IOSuccess()`](#returns.io.IOSuccess "returns.io.IOSuccess") and [`IOFailure()`](#returns.io.IOFailure "returns.io.IOFailure") public type constructors

* You can construct `IOResult` from `IO` values

with [`from\_failed\_io()`](#returns.io.IOResult.from_failed_io "returns.io.IOResult.from_failed_io")

and [`IOResult.from\_io()`](#returns.io.IOResult.from_io "returns.io.IOResult.from_io")

* You can construct `IOResult` from `Result` values

with [`from\_result()`](#returns.io.IOResult.from_result "returns.io.IOResult.from_result")

We also have a lot of utility methods for better function composition like:

* [`bind\_result()`](#returns.io.IOResult.bind_result "returns.io.IOResult.bind_result") to work

with functions which return `Result`

* [`from\_typecast()`](#returns.io.IOResult.from_typecast "returns.io.IOResult.from_typecast") to work with `IO[Result[...]]` values

See also

<https://github.com/gcanti/fp-ts/blob/master/docs/modules/IOEither.ts.md>

Implementation

This class contains all the methods that can be delegated to `Result`.

But, some methods are not implemented which means

that we have to use special `\_IOSuccess` and `\_IOFailure`

implementation details to correctly handle these callbacks.

Do not rely on them! Use public functions and types instead.

Parameters:

**inner\_value** ([`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_ErrorType`, covariant=True)]) – 

success\_type[¶](#returns.io.IOResult.success_type "Permalink to this definition")

Success type that is used to represent the successful computation.

Parameters:

**inner\_value** (`TypeVar`(`\_ValueType`, covariant=True)) – 

alias of [`IOSuccess`](#returns.io.IOSuccess "returns.io.IOSuccess")

failure\_type[¶](#returns.io.IOResult.failure_type "Permalink to this definition")

Failure type that is used to represent the failed computation.

Parameters:

**inner\_value** (`TypeVar`(`\_ErrorType`, covariant=True)) – 

alias of [`IOFailure`](#returns.io.IOFailure "returns.io.IOFailure")

equals(*other*)[¶](#returns.io.IOResult.equals "Permalink to this definition")

Typesafe equality comparison with other IOResult objects.

Parameters:

* **self** ([`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_EqualType`, bound= [`Equable`](index.html#returns.interfaces.equable.Equable "returns.interfaces.equable.Equable")), `Any`, `Any`, `Any`]) –

* **other** ([`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_EqualType`, bound= [`Equable`](index.html#returns.interfaces.equable.Equable "returns.interfaces.equable.Equable")), `Any`, `Any`, `Any`]) –

Return type:

`bool`

*property* trace*: Optional[List[FrameInfo]]*[¶](#returns.io.IOResult.trace "Permalink to this definition")

Returns a stack trace when [`IOFailure()`](#returns.io.IOFailure "returns.io.IOFailure") was called.

swap()[[source]](_modules/returns/io.html#IOResult.swap)[¶](#returns.io.IOResult.swap "Permalink to this definition")

Swaps value and error types.

So, values become errors and errors become values.

It is useful when you have to work with errors a lot.

And since we have a lot of `.bind\_` related methods

and only a single `.lash` - it is easier to work with values.

```

>>> from returns.io import IOSuccess, IOFailure

>>> assert IOSuccess(1).swap() == IOFailure(1)

>>> assert IOFailure(1).swap() == IOSuccess(1)

```

Return type:

[`IOResult`](#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_ValueType`, covariant=True)]

map(*function*)[[source]](_modules/returns/io.html#IOResult.map)[¶](#returns.io.IOResult.map "Permalink to this definition")

Composes successful container with a pure function.

```

>>> from returns.io import IOSuccess

>>> assert IOSuccess(1).map(lambda num: num + 1) == IOSuccess(2)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `TypeVar`(`\_NewValueType`)]) – 

Return type:

[`IOResult`](#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]

apply(*container*)[[source]](_modules/returns/io.html#IOResult.apply)[¶](#returns.io.IOResult.apply "Permalink to this definition")

Calls a wrapped function in a container on this container.

```

>>> from returns.io import IOSuccess, IOFailure

>>> def appliable(first: str) -> str:

...      return first + 'b'

>>> assert IOSuccess('a').apply(

...     IOSuccess(appliable),

... ) == IOSuccess('ab')

>>> assert IOFailure('a').apply(

...     IOSuccess(appliable),

... ) == IOFailure('a')

>>> assert IOSuccess('a').apply(IOFailure(1)) == IOFailure(1)

>>> assert IOFailure('a').apply(IOFailure('b')) == IOFailure('a')

```

Parameters:

**container** ([`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`IOResult`](#returns.io.IOResult "returns.io.IOResult"), `Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `TypeVar`(`\_NewValueType`)], `TypeVar`(`\_ErrorType`, covariant=True), `Any`]) – 

Return type:

[`IOResult`](#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]

bind(*function*)[[source]](_modules/returns/io.html#IOResult.bind)[¶](#returns.io.IOResult.bind "Permalink to this definition")

Composes successful container with a function that returns a container.

```

>>> from returns.io import IOResult, IOFailure, IOSuccess

>>> def bindable(string: str) -> IOResult[str, str]:

...      if len(string) > 1:

...          return IOSuccess(string + 'b')

...      return IOFailure(string + 'c')

>>> assert IOSuccess('aa').bind(bindable) == IOSuccess('aab')

>>> assert IOSuccess('a').bind(bindable) == IOFailure('ac')

>>> assert IOFailure('a').bind(bindable) == IOFailure('a')

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`IOResult`](#returns.io.IOResult "returns.io.IOResult"), `TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `Any`]]) – 

Return type:

[`IOResult`](#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]

bind\_ioresult(*function*)[¶](#returns.io.IOResult.bind_ioresult "Permalink to this definition")

Alias for bind\_ioresult method. Part of the IOResultBasedN interface.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`IOResult`](#returns.io.IOResult "returns.io.IOResult"), `TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `Any`]]) – 

Return type:

[`IOResult`](#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]

bind\_result(*function*)[[source]](_modules/returns/io.html#IOResult.bind_result)[¶](#returns.io.IOResult.bind_result "Permalink to this definition")

Composes successful container with a function that returns a container.

Similar to [`bind()`](#returns.io.IOResult.bind "returns.io.IOResult.bind"), but works with containers

that return [`returns.result.Result`](index.html#returns.result.Result "returns.result.Result")

instead of [`IOResult`](#returns.io.IOResult "returns.io.IOResult").

```

>>> from returns.io import IOFailure, IOSuccess

>>> from returns.result import Result, Success

>>> def bindable(string: str) -> Result[str, str]:

...      if len(string) > 1:

...          return Success(string + 'b')

...      return Failure(string + 'c')

>>> assert IOSuccess('aa').bind\_result(bindable) == IOSuccess('aab')

>>> assert IOSuccess('a').bind\_result(bindable) == IOFailure('ac')

>>> assert IOFailure('a').bind\_result(bindable) == IOFailure('a')

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]]) – 

Return type:

[`IOResult`](#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]

bind\_io(*function*)[[source]](_modules/returns/io.html#IOResult.bind_io)[¶](#returns.io.IOResult.bind_io "Permalink to this definition")

Composes successful container with a function that returns a container.

Similar to [`bind()`](#returns.io.IOResult.bind "returns.io.IOResult.bind"), but works with containers

that return [`returns.io.IO`](#returns.io.IO "returns.io.IO") instead of [`IOResult`](#returns.io.IOResult "returns.io.IOResult").

```

>>> from returns.io import IO, IOFailure, IOSuccess

>>> def bindable(string: str) -> IO[str]:

...      return IO(string + 'z')

>>> assert IOSuccess('a').bind\_io(bindable) == IOSuccess('az')

>>> assert IOFailure('a').bind\_io(bindable) == IOFailure('a')

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`IO`](#returns.io.IO "returns.io.IO")[`TypeVar`(`\_NewValueType`)]]) – 

Return type:

[`IOResult`](#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]

alt(*function*)[[source]](_modules/returns/io.html#IOResult.alt)[¶](#returns.io.IOResult.alt "Permalink to this definition")

Composes failed container with a pure function to modify failure.

```

>>> from returns.io import IOFailure

>>> assert IOFailure(1).alt(float) == IOFailure(1.0)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ErrorType`, covariant=True)], `TypeVar`(`\_NewErrorType`)]) – 

Return type:

[`IOResult`](#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_NewErrorType`)]

lash(*function*)[[source]](_modules/returns/io.html#IOResult.lash)[¶](#returns.io.IOResult.lash "Permalink to this definition")

Composes failed container with a function that returns a container.

```

>>> from returns.io import IOFailure, IOSuccess, IOResult

>>> def lashable(state: str) -> IOResult[int, str]:

...     if len(state) > 1:

...         return IOSuccess(len(state))

...     return IOFailure('oops')

>>> assert IOFailure('a').lash(lashable) == IOFailure('oops')

>>> assert IOFailure('abc').lash(lashable) == IOSuccess(3)

>>> assert IOSuccess('a').lash(lashable) == IOSuccess('a')

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ErrorType`, covariant=True)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`IOResult`](#returns.io.IOResult "returns.io.IOResult"), `TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_NewErrorType`), `Any`]]) – 

Return type:

[`IOResult`](#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_NewErrorType`)]

value\_or(*default\_value*)[[source]](_modules/returns/io.html#IOResult.value_or)[¶](#returns.io.IOResult.value_or "Permalink to this definition")

Get value from successful container or default value from failed one.

```

>>> from returns.io import IO, IOFailure, IOSuccess

>>> assert IOSuccess(1).value\_or(None) == IO(1)

>>> assert IOFailure(1).value\_or(None) == IO(None)

```

Parameters:

**default\_value** (`TypeVar`(`\_NewValueType`)) – 

Return type:

[`IO`](#returns.io.IO "returns.io.IO")[`Union`[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_NewValueType`)]]

unwrap()[[source]](_modules/returns/io.html#IOResult.unwrap)[¶](#returns.io.IOResult.unwrap "Permalink to this definition")

Get value from successful container or raise exception for failed one.

```

>>> from returns.io import IO, IOFailure, IOSuccess

>>> assert IOSuccess(1).unwrap() == IO(1)

>>> IOFailure(1).unwrap()

Traceback (most recent call last):

 ...

returns.primitives.exceptions.UnwrapFailedError

```

Return type:

[`IO`](#returns.io.IO "returns.io.IO")[`TypeVar`(`\_ValueType`, covariant=True)]

failure()[[source]](_modules/returns/io.html#IOResult.failure)[¶](#returns.io.IOResult.failure "Permalink to this definition")

Get failed value from failed container or raise exception from success.

```

>>> from returns.io import IO, IOFailure, IOSuccess

>>> assert IOFailure(1).failure() == IO(1)

>>> IOSuccess(1).failure()

Traceback (most recent call last):

 ...

returns.primitives.exceptions.UnwrapFailedError

```

Return type:

[`IO`](#returns.io.IO "returns.io.IO")[`TypeVar`(`\_ErrorType`, covariant=True)]

compose\_result(*function*)[[source]](_modules/returns/io.html#IOResult.compose_result)[¶](#returns.io.IOResult.compose_result "Permalink to this definition")

Composes inner `Result` with `IOResult` returning function.

Can be useful when you need an access to both states of the result.

```

>>> from returns.io import IOResult, IOSuccess, IOFailure

>>> from returns.result import Result

>>> def count(container: Result[int, int]) -> IOResult[int, int]:

...     return IOResult.from\_result(

...         container.map(lambda x: x + 1).alt(abs),

...     )

>>> assert IOSuccess(1).compose\_result(count) == IOSuccess(2)

>>> assert IOFailure(-1).compose\_result(count) == IOFailure(1)

```

Parameters:

**function** (`Callable`[[[`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_ErrorType`, covariant=True)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`IOResult`](#returns.io.IOResult "returns.io.IOResult"), `TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `Any`]]) – 

Return type:

[`IOResult`](#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]

*classmethod* do(*expr*)[[source]](_modules/returns/io.html#IOResult.do)[¶](#returns.io.IOResult.do "Permalink to this definition")

Allows working with unwrapped values of containers in a safe way.

```

>>> from returns.io import IOResult, IOFailure, IOSuccess

>>> assert IOResult.do(

...     first + second

...     for first in IOSuccess(2)

...     for second in IOSuccess(3)

... ) == IOSuccess(5)

>>> assert IOResult.do(

...     first + second

...     for first in IOFailure('a')

...     for second in IOSuccess(3)

... ) == IOFailure('a')

```

See [Do Notation](index.html#do-notation) to learn more.

This feature requires our [mypy plugin](index.html#mypy-plugins).

Parameters:

**expr** (`Generator`[`TypeVar`(`\_NewValueType`), `None`, `None`]) – 

Return type:

[`IOResult`](#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]

*classmethod* from\_typecast(*inner\_value*)[[source]](_modules/returns/io.html#IOResult.from_typecast)[¶](#returns.io.IOResult.from_typecast "Permalink to this definition")

Converts `IO[Result[\_ValueType, \_ErrorType]]` to `IOResult`.

Also prevails the type of `Result` to `IOResult`, so:

`IO[Result[\_ValueType, \_ErrorType]]` would become

`IOResult[\_ValueType, \_ErrorType]`.

```

>>> from returns.result import Success

>>> from returns.io import IO, IOResult, IOSuccess

>>> container = IO(Success(1))

>>> assert IOResult.from\_typecast(container) == IOSuccess(1)

```

Can be reverted via [`returns.io.IO.from\_ioresult()`](#returns.io.IO.from_ioresult "returns.io.IO.from_ioresult") method.

Parameters:

**inner\_value** ([`IO`](#returns.io.IO "returns.io.IO")[[`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]]) – 

Return type:

[`IOResult`](#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]

*classmethod* from\_failed\_io(*inner\_value*)[[source]](_modules/returns/io.html#IOResult.from_failed_io)[¶](#returns.io.IOResult.from_failed_io "Permalink to this definition")

Creates new `IOResult` from “failed” `IO` container.

```

>>> from returns.io import IO, IOResult, IOFailure

>>> container = IO(1)

>>> assert IOResult.from\_failed\_io(container) == IOFailure(1)

```

Parameters:

**inner\_value** ([`IO`](#returns.io.IO "returns.io.IO")[`TypeVar`(`\_NewErrorType`)]) – 

Return type:

[`IOResult`](#returns.io.IOResult "returns.io.IOResult")[`Any`, `TypeVar`(`\_NewErrorType`)]

*classmethod* from\_io(*inner\_value*)[[source]](_modules/returns/io.html#IOResult.from_io)[¶](#returns.io.IOResult.from_io "Permalink to this definition")

Creates new `IOResult` from “successful” `IO` container.

```

>>> from returns.io import IO, IOResult, IOSuccess

>>> container = IO(1)

>>> assert IOResult.from\_io(container) == IOSuccess(1)

```

Parameters:

**inner\_value** ([`IO`](#returns.io.IO "returns.io.IO")[`TypeVar`(`\_NewValueType`)]) – 

Return type:

[`IOResult`](#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_NewValueType`), `Any`]

*classmethod* from\_result(*inner\_value*)[[source]](_modules/returns/io.html#IOResult.from_result)[¶](#returns.io.IOResult.from_result "Permalink to this definition")

Creates `IOResult` from `Result` value.

```

>>> from returns.io import IOResult, IOSuccess, IOFailure

>>> from returns.result import Success, Failure

>>> assert IOResult.from\_result(Success(1)) == IOSuccess(1)

>>> assert IOResult.from\_result(Failure(2)) == IOFailure(2)

```

Parameters:

**inner\_value** ([`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]) – 

Return type:

[`IOResult`](#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]

*classmethod* from\_ioresult(*inner\_value*)[[source]](_modules/returns/io.html#IOResult.from_ioresult)[¶](#returns.io.IOResult.from_ioresult "Permalink to this definition")

Creates `IOResult` from existing `IOResult` value.

```

>>> from returns.io import IOResult, IOSuccess, IOFailure

>>> assert IOResult.from\_ioresult(IOSuccess(1)) == IOSuccess(1)

>>> assert IOResult.from\_ioresult(IOFailure(2)) == IOFailure(2)

```

Parameters:

**inner\_value** ([`IOResult`](#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]) – 

Return type:

[`IOResult`](#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]

*classmethod* from\_value(*inner\_value*)[[source]](_modules/returns/io.html#IOResult.from_value)[¶](#returns.io.IOResult.from_value "Permalink to this definition")

One more value to create success unit values.

It is useful as a united way to create a new value from any container.

```

>>> from returns.io import IOResult, IOSuccess

>>> assert IOResult.from\_value(1) == IOSuccess(1)

```

You can use this method or [`IOSuccess()`](#returns.io.IOSuccess "returns.io.IOSuccess"),

choose the most convenient for you.

Parameters:

**inner\_value** (`TypeVar`(`\_NewValueType`)) – 

Return type:

[`IOResult`](#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_NewValueType`), `Any`]

*classmethod* from\_failure(*inner\_value*)[[source]](_modules/returns/io.html#IOResult.from_failure)[¶](#returns.io.IOResult.from_failure "Permalink to this definition")

One more value to create failure unit values.

It is useful as a united way to create a new value from any container.

```

>>> from returns.io import IOResult, IOFailure

>>> assert IOResult.from\_failure(1) == IOFailure(1)

```

You can use this method or [`IOFailure()`](#returns.io.IOFailure "returns.io.IOFailure"),

choose the most convenient for you.

Parameters:

**inner\_value** (`TypeVar`(`\_NewErrorType`)) – 

Return type:

[`IOResult`](#returns.io.IOResult "returns.io.IOResult")[`Any`, `TypeVar`(`\_NewErrorType`)]

*final class* IOFailure(*inner\_value*)[[source]](_modules/returns/io.html#IOFailure)[¶](#returns.io.IOFailure "Permalink to this definition")

Bases: [`IOResult`](#returns.io.IOResult "returns.io.IOResult")[`Any`, `\_ErrorType`]

`IOFailure` representation.

Parameters:

**inner\_value** (`TypeVar`(`\_ErrorType`, covariant=True)) – 

bind(*function*)[[source]](_modules/returns/io.html#IOFailure.bind)[¶](#returns.io.IOFailure.bind "Permalink to this definition")

Does nothing for `IOFailure`.

bind\_ioresult(*function*)[¶](#returns.io.IOFailure.bind_ioresult "Permalink to this definition")

Alias for bind\_ioresult method. Part of the IOResultBasedN interface. # noqa: E501

bind\_result(*function*)[[source]](_modules/returns/io.html#IOFailure.bind_result)[¶](#returns.io.IOFailure.bind_result "Permalink to this definition")

Does nothing for `IOFailure`.

bind\_io(*function*)[[source]](_modules/returns/io.html#IOFailure.bind_io)[¶](#returns.io.IOFailure.bind_io "Permalink to this definition")

Does nothing for `IOFailure`.

lash(*function*)[[source]](_modules/returns/io.html#IOFailure.lash)[¶](#returns.io.IOFailure.lash "Permalink to this definition")

Composes this container with a function returning `IOResult`.

*final class* IOSuccess(*inner\_value*)[[source]](_modules/returns/io.html#IOSuccess)[¶](#returns.io.IOSuccess "Permalink to this definition")

Bases: [`IOResult`](#returns.io.IOResult "returns.io.IOResult")[`\_ValueType`, `Any`]

`IOSuccess` representation.

Parameters:

**inner\_value** (`TypeVar`(`\_ValueType`, covariant=True)) – 

bind(*function*)[[source]](_modules/returns/io.html#IOSuccess.bind)[¶](#returns.io.IOSuccess.bind "Permalink to this definition")

Composes this container with a function returning `IOResult`.

bind\_ioresult(*function*)[¶](#returns.io.IOSuccess.bind_ioresult "Permalink to this definition")

Alias for bind\_ioresult method. Part of the IOResultBasedN interface. # noqa: E501

bind\_result(*function*)[[source]](_modules/returns/io.html#IOSuccess.bind_result)[¶](#returns.io.IOSuccess.bind_result "Permalink to this definition")

Binds `Result` returning function to current container.

bind\_io(*function*)[[source]](_modules/returns/io.html#IOSuccess.bind_io)[¶](#returns.io.IOSuccess.bind_io "Permalink to this definition")

Binds `IO` returning function to current container.

lash(*function*)[[source]](_modules/returns/io.html#IOSuccess.lash)[¶](#returns.io.IOSuccess.lash "Permalink to this definition")

Does nothing for `IOSuccess`.

IOResultE[¶](#returns.io.IOResultE "Permalink to this definition")

Alias for a popular case when `IOResult` has `Exception` as error type.

alias of [`IOResult`](#returns.io.IOResult "returns.io.IOResult")[`\_ValueType`, `Exception`]

impure\_safe(*function*)[[source]](_modules/returns/io.html#impure_safe)[¶](#returns.io.impure_safe "Permalink to this definition")

Decorator to mark function that it returns [`IOResult`](#returns.io.IOResult "returns.io.IOResult") container.

Should be used with care, since it only catches `Exception` subclasses.

It does not catch `BaseException` subclasses.

If you need to mark `async` function as impure,

use [`returns.future.future\_safe()`](index.html#returns.future.future_safe "returns.future.future_safe") instead.

This decorator only works with sync functions. Example:

```

>>> from returns.io import IOSuccess, impure\_safe

>>> @impure\_safe

... def function(arg: int) -> float:

...     return 1 / arg

...

>>> assert function(1) == IOSuccess(1.0)

>>> assert function(0).failure()

```

Similar to [`returns.future.future\_safe()`](index.html#returns.future.future_safe "returns.future.future_safe")

and [`returns.result.safe()`](index.html#returns.result.safe "returns.result.safe") decorators.

Parameters:

**function** (`Callable`[[`ParamSpec`(`\_FuncParams`)], `TypeVar`(`\_NewValueType`)]) – 

Return type:

`Callable`[[`ParamSpec`(`\_FuncParams`)], [`IOResult`](#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_NewValueType`), `Exception`]]

unsafe\_perform\_io(*wrapped\_in\_io*)[[source]](_modules/returns/unsafe.html#unsafe_perform_io)[¶](#returns.unsafe.unsafe_perform_io "Permalink to this definition")

Compatibility utility and escape mechanism from `IO` world.

Just unwraps the internal value

from [`returns.io.IO`](#returns.io.IO "returns.io.IO") container.

Should be used with caution!

Since it might be overused by lazy and ignorant developers.

It is recommended to have only one place (module / file)

in your program where you allow unsafe operations.

We recommend to use `import-linter` to enforce this rule.

```

>>> from returns.io import IO

>>> assert unsafe\_perform\_io(IO(1)) == 1

```

See also

* <https://github.com/seddonym/import-linter>

Parameters:

**wrapped\_in\_io** ([`IO`](#returns.io.IO "returns.io.IO")[`TypeVar`(`\_ValueType`)]) – 

Return type:

`TypeVar`(`\_ValueType`)

Future[¶](#future "Permalink to this heading")

----------------------------------------------

A set of primitives to work with `async` functions.

Can be used with `asyncio`, `trio`, and `curio`.

And any event-loop!

Tested with [anyio](https://github.com/agronholm/anyio).

What problems do we solve with these containers? Basically these ones:

1. You cannot call async function from a sync one

2. Any unexpectedly thrown exception can ruin your whole event loop

3. Ugly composition with lots of await statements

### Future container[¶](#future-container "Permalink to this heading")

Without `Future` container it is impossible to compose two functions:

sync and async one.

You simply cannot `await` coroutines inside a sync context.

It is even a `SyntaxError`.

```

def test():

    await some()

# SyntaxError: 'await' outside async function

```

So, you have to turn you function into async one.

And all callers of this function in async functions. And all their callers.

This is really hard to model.

When you code has two types of uncomposable

functions you increase your mental complexity by extreme levels.

Instead, you can use `Future` container,

it allows you to model async interactions in a sync manner:

```

>>> from returns.future import Future

>>> async def first() -> int:

...     return 1

>>> async def second(arg: int) -> int:

...     return arg + 1

>>> def main() -> Future[int]:  # sync function!

...    return Future(first()).bind\_awaitable(second)

```

Now we can compose async functions and maintaining a sync context!

It is also possible run a `Future`

with regular tools like `asyncio.run` or `anyio.run`:

```

>>> import anyio

>>> from returns.io import IO

>>> assert anyio.run(main().awaitable) == IO(2)

```

One more very useful thing `Future` does behind the scenes is converting

its result to `IO`-based containers.

This helps a lot when separating pure and impure

(async functions are impure) code inside your app.

### FutureResult[¶](#futureresult "Permalink to this heading")

This container becomes very useful when working

with `async` function that can fail.

It works the similar way regular `Result` does.

And is literally a wrapper around `Future[Result[\_V, \_E]]` type.

Let’s see how it can be used in a real program:

```

 1import asyncio  # we use `asyncio` only as an example, you can use any io lib

 2from typing import Final, Sequence, cast

 3

 4import httpx  # you would need to `pip install httpx`

 5from typing\_extensions import TypedDict

 6

 7from returns.future import FutureResultE, future\_safe

 8from returns.io import IOResultE

 9from returns.iterables import Fold

10

11\_URL: Final = 'https://jsonplaceholder.typicode.com/posts/{0}'

12

13

14class \_Post(TypedDict):

15    id: int

16    user\_id: int

17    title: str

18    body: str

19

20

21@future\_safe

22async def \_fetch\_post(post\_id: int) -> \_Post:

23    # Ideally, we can use `ReaderFutureResult` to provide `client` from deps.

24    async with httpx.AsyncClient(timeout=5) as client:

25        response = await client.get(\_URL.format(post\_id))

26        response.raise\_for\_status()

27        return cast(\_Post, response.json())  # or validate the response

28

29

30def \_show\_titles(number\_of\_posts: int) -> Sequence[FutureResultE[str]]:

31    def factory(post: \_Post) -> str:

32        return post['title']

33

34    return [

35        # Notice how easily we compose async and sync functions:

36        \_fetch\_post(post\_id).map(factory)

37        # TODO: try `for post\_id in (2, 1, 0):` to see how async errors work

38        for post\_id in range(1, number\_of\_posts + 1)

39    ]

40

41

42async def main() -> IOResultE[Sequence[str]]:

43 """

44 Main entrypoint for the async world.

45

46 Let's fetch 3 titles of posts asynchronously.

47 We use `gather` to run requests in "parallel".

48 """

49    futures: Sequence[IOResultE[str]] = await asyncio.gather(\*\_show\_titles(3))

50    return Fold.collect(futures, IOResultE.from\_value(()))

51

52

53if \_\_name\_\_ == '\_\_main\_\_':

54    print(asyncio.run(main()))  # noqa: WPS421

55    # <IOResult: <Success: (

56    # 'sunt aut facere repellat provident occaecati ...',

57    # 'qui est esse',

58    # 'ea molestias quasi exercitationem repellat qui ipsa sit aut',

59    # )>>

```

What is different?

1. We can now easily make `show\_titles` sync,

we can also make `\_fetch\_post` sync,

but we would need to use `ReaderFutureResult` container

with proper dependencies in this case

2. We now don’t care about errors at all.

In this example any error will cancel the whole pipeline

3. We now have `.map` method to easily compose sync and async functions

You can see the next example

with [RequiresContextFutureResult](index.html#requires-context-future-result)

and without a single `async/await`.

That example illustrates the whole point of our actions: writing

sync code that executes asynchronously without any magic at all.

### Aliases[¶](#aliases "Permalink to this heading")

There are several useful alises for `FutureResult` type

with some common values:

* [`returns.future.FutureResultE`](#returns.future.FutureResultE "returns.future.FutureResultE") is an alias

for `FutureResult[... Exception]`,

just use it when you want to work with `FutureResult` containers

that use exceptions as error type.

It is named `FutureResultE` because it is `FutureResultException`

and `FutureResultError` at the same time.

### Decorators[¶](#decorators "Permalink to this heading")

#### future[¶](#id1 "Permalink to this heading")

This decorator helps to easily transform `async def` into `Future`:

```

>>> import anyio

>>> from returns.future import future, Future

>>> from returns.io import IO

>>> @future

... async def test(arg: int) -> float:

...     return arg / 2

>>> future\_instance = test(1)

>>> assert isinstance(future\_instance, Future)

>>> assert anyio.run(future\_instance.awaitable) == IO(0.5)

```

Make sure that you decorate with `@future` only coroutines

that do not throw exceptions. For ones that do, use `future\_safe`.

#### future\_safe[¶](#future-safe "Permalink to this heading")

This decorator converts `async def` into `FutureResult`,

which means that it becomes:

1. Full featured `Future` like container

2. Safe from any exceptions

Let’s dig into it:

```

>>> import anyio

>>> from returns.future import future\_safe, FutureResult

>>> from returns.io import IOSuccess, IOFailure

>>> @future\_safe

... async def test(arg: int) -> float:

...     return 1 / arg

>>> future\_instance = test(2)

>>> assert isinstance(future\_instance, FutureResult)

>>> assert anyio.run(future\_instance.awaitable) == IOSuccess(0.5)

>>> str(anyio.run(test(0).awaitable))  # this will fail

'<IOResult: <Failure: division by zero>>'

```

Never miss exceptions ever again!

#### asyncify[¶](#asyncify "Permalink to this heading")

Helper decorator to transform regular sync function into `async` ones.

```

>>> import anyio

>>> from inspect import iscoroutinefunction

>>> from returns.future import asyncify

>>> @asyncify

... def your\_function(x: int) -> int:

...     return x + 1

>>> assert iscoroutinefunction(your\_function) is True

>>> assert anyio.run(your\_function, 1) == 2

```

Very important node: making your function `async` does not mean

it will work asynchronously. It can still block if it uses blocking calls.

Here’s an example of how you **must not** do:

```

import requests

from returns.future import asyncify

@asyncify

def please\_do\_not\_do\_that():

    return requests.get('...')  # this will still block!

```

Do not overuse this decorator.

It is only useful for some basic composition

with `Future` and `FutureResult`.

### FAQ[¶](#faq "Permalink to this heading")

#### Is it somehow related to Future object from asyncio?[¶](#is-it-somehow-related-to-future-object-from-asyncio "Permalink to this heading")

Nope, we just use the same naming there are in other languages and platforms.

Python happens to have its own meaning for this word.

In our worldview, these two `Future` entities should never meet each other

in a single codebase.

It is also not related to [concurrent.Future](https://docs.python.org/3/library/concurrent.futures.html).

#### How to create unit objects?[¶](#how-to-create-unit-objects "Permalink to this heading")

For `Future` container:

* `from\_value` when you have a raw value

* `from\_io` when you have existing `IO` container

* `from\_future\_result` when you have existing `FutureResult`

For `FutureResult` container:

* `from\_value` when you want to mark some raw value as a `Success`

* `from\_failure` when you want to mark some raw value as a `Failure`

* `from\_result` when you already have `Result` container

* `from\_io` when you have successful `IO`

* `from\_failed\_io` when you have failed `IO`

* `from\_future` when you have successful `Future`

* `from\_failed\_future` when you have failed `Future`

* `from\_typecast` when you have existing `Future[Result]`

#### What is the difference between Future[Result[a, b]] and FutureResult[a, b]?[¶](#what-is-the-difference-between-future-result-a-b-and-futureresult-a-b "Permalink to this heading")

There’s almost none.

The only difference is that `FutureResult[a, b]` is a handy wrapper

around `Future[Result[a, b]]`,

so you won’t need to use methods like `.map` and `.bind` twice.

You can always convert it with methods like

`.from\_typecast` and `.from\_future\_result`.

### Further reading[¶](#further-reading "Permalink to this heading")

* [How Async Should Have Been](https://sobolevn.me/2020/06/how-async-should-have-been)

* [What Color is Your Function?](https://journal.stuffwithstuff.com/2015/02/01/what-color-is-your-function/)

* [From Promises to Futures](https://dev.to/nadeesha/from-promises-to-futures-in-javascript-2m6g)

### API Reference[¶](#api-reference "Permalink to this heading")

 classDiagram

 BaseContainer <|-- Future

 BaseContainer <|-- FutureResult

 FutureBasedN <|-- Future

 FutureResultBasedN <|-- FutureResult

 SupportsKindN <|-- Future

 SupportsKindN <|-- FutureResult

 

*async* async\_identity(*instance*)[[source]](_modules/returns/future.html#async_identity)[¶](#returns.future.async_identity "Permalink to this definition")

Async function that returns its argument.

```

>>> import anyio

>>> from returns.future import async\_identity

>>> assert anyio.run(async\_identity, 1) == 1

```

See [`returns.functions.identity()`](index.html#returns.functions.identity "returns.functions.identity")

for sync version of this function and more docs and examples.

Parameters:

**instance** (`TypeVar`(`\_FirstType`)) – 

Return type:

`TypeVar`(`\_FirstType`)

*final class* Future(*inner\_value*)[[source]](_modules/returns/future.html#Future)[¶](#returns.future.Future "Permalink to this definition")

Bases: [`BaseContainer`](index.html#returns.primitives.container.BaseContainer "returns.primitives.container.BaseContainer"), [`SupportsKindN`](index.html#returns.primitives.hkt.SupportsKindN "returns.primitives.hkt.SupportsKindN")[[`Future`](#returns.future.Future "returns.future.Future"), `\_ValueType`, `NoReturn`, `NoReturn`], [`FutureBasedN`](index.html#returns.interfaces.specific.future.FutureBasedN "returns.interfaces.specific.future.FutureBasedN")[`\_ValueType`, `NoReturn`, `NoReturn`]

Container to easily compose `async` functions.

Represents a better abstraction over a simple coroutine.

Is framework, event-loop, and IO-library agnostics.

Works with `asyncio`, `curio`, `trio`, or any other tool.

Internally we use `anyio` to test

that it works as expected for any io stack.

Note that `Future[a]` represents a computation

that never fails and returns `IO[a]` type.

Use `FutureResult[a, b]` for operations that might fail.

Like DB access or network operations.

Is not related to `asyncio.Future` in any kind.

Tradeoffs

Due to possible performance issues we move all coroutines definitions

to a separate module.

See also

* <https://gcanti.github.io/fp-ts/modules/Task.ts.html>

* <https://zio.dev/docs/overview/overview_basic_concurrency>

Parameters:

**inner\_value** (`Awaitable`[`TypeVar`(`\_ValueType`, covariant=True)]) – 

*async* awaitable()[[source]](_modules/returns/future.html#Future.awaitable)[¶](#returns.future.Future.awaitable "Permalink to this definition")

Transforms `Future[a]` to `Awaitable[IO[a]]`.

Use this method when you need a real coroutine.

Like for `asyncio.run` calls.

Note, that returned value will be wrapped

in [`returns.io.IO`](index.html#returns.io.IO "returns.io.IO") container.

```

>>> import anyio

>>> from returns.future import Future

>>> from returns.io import IO

>>> assert anyio.run(Future.from\_value(1).awaitable) == IO(1)

```

Return type:

[`IO`](index.html#returns.io.IO "returns.io.IO")[`TypeVar`(`\_ValueType`, covariant=True)]

map(*function*)[[source]](_modules/returns/future.html#Future.map)[¶](#returns.future.Future.map "Permalink to this definition")

Applies function to the inner value.

Applies ‘function’ to the contents of the IO instance

and returns a new `Future` object containing the result.

‘function’ should accept a single “normal” (non-container) argument

and return a non-container result.

```

>>> import anyio

>>> from returns.future import Future

>>> from returns.io import IO

>>> def mappable(x: int) -> int:

...    return x + 1

>>> assert anyio.run(

...     Future.from\_value(1).map(mappable).awaitable,

... ) == IO(2)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `TypeVar`(`\_NewValueType`)]) – 

Return type:

[`Future`](#returns.future.Future "returns.future.Future")[`TypeVar`(`\_NewValueType`)]

apply(*container*)[[source]](_modules/returns/future.html#Future.apply)[¶](#returns.future.Future.apply "Permalink to this definition")

Calls a wrapped function in a container on this container.

```

>>> import anyio

>>> from returns.future import Future

>>> def transform(arg: int) -> str:

...      return str(arg) + 'b'

>>> assert anyio.run(

...     Future.from\_value(1).apply(

...         Future.from\_value(transform),

...     ).awaitable,

... ) == IO('1b')

```

Parameters:

**container** ([`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`Future`](#returns.future.Future "returns.future.Future"), `Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `TypeVar`(`\_NewValueType`)], `Any`, `Any`]) – 

Return type:

[`Future`](#returns.future.Future "returns.future.Future")[`TypeVar`(`\_NewValueType`)]

bind(*function*)[[source]](_modules/returns/future.html#Future.bind)[¶](#returns.future.Future.bind "Permalink to this definition")

Applies ‘function’ to the result of a previous calculation.

‘function’ should accept a single “normal” (non-container) argument

and return `Future` type object.

```

>>> import anyio

>>> from returns.future import Future

>>> from returns.io import IO

>>> def bindable(x: int) -> Future[int]:

...    return Future.from\_value(x + 1)

>>> assert anyio.run(

...     Future.from\_value(1).bind(bindable).awaitable,

... ) == IO(2)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`Future`](#returns.future.Future "returns.future.Future"), `TypeVar`(`\_NewValueType`), `Any`, `Any`]]) – 

Return type:

[`Future`](#returns.future.Future "returns.future.Future")[`TypeVar`(`\_NewValueType`)]

bind\_future(*function*)[¶](#returns.future.Future.bind_future "Permalink to this definition")

Alias for bind method. Part of the FutureBasedN interface.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`Future`](#returns.future.Future "returns.future.Future"), `TypeVar`(`\_NewValueType`), `Any`, `Any`]]) – 

Return type:

[`Future`](#returns.future.Future "returns.future.Future")[`TypeVar`(`\_NewValueType`)]

bind\_async(*function*)[[source]](_modules/returns/future.html#Future.bind_async)[¶](#returns.future.Future.bind_async "Permalink to this definition")

Compose a container and `async` function returning a container.

This function should return a container value.

See [`bind\_awaitable()`](#returns.future.Future.bind_awaitable "returns.future.Future.bind_awaitable")

to bind `async` function that returns a plain value.

```

>>> import anyio

>>> from returns.future import Future

>>> from returns.io import IO

>>> async def coroutine(x: int) -> Future[str]:

...    return Future.from\_value(str(x + 1))

>>> assert anyio.run(

...     Future.from\_value(1).bind\_async(coroutine).awaitable,

... ) == IO('2')

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `Awaitable`[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`Future`](#returns.future.Future "returns.future.Future"), `TypeVar`(`\_NewValueType`), `Any`, `Any`]]]) – 

Return type:

[`Future`](#returns.future.Future "returns.future.Future")[`TypeVar`(`\_NewValueType`)]

bind\_async\_future(*function*)[¶](#returns.future.Future.bind_async_future "Permalink to this definition")

Alias for bind\_async method. Part of the FutureBasedN interface.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `Awaitable`[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`Future`](#returns.future.Future "returns.future.Future"), `TypeVar`(`\_NewValueType`), `Any`, `Any`]]]) – 

Return type:

[`Future`](#returns.future.Future "returns.future.Future")[`TypeVar`(`\_NewValueType`)]

bind\_awaitable(*function*)[[source]](_modules/returns/future.html#Future.bind_awaitable)[¶](#returns.future.Future.bind_awaitable "Permalink to this definition")

Allows to compose a container and a regular `async` function.

This function should return plain, non-container value.

See [`bind\_async()`](#returns.future.Future.bind_async "returns.future.Future.bind_async")

to bind `async` function that returns a container.

```

>>> import anyio

>>> from returns.future import Future

>>> from returns.io import IO

>>> async def coroutine(x: int) -> int:

...    return x + 1

>>> assert anyio.run(

...     Future.from\_value(1).bind\_awaitable(coroutine).awaitable,

... ) == IO(2)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `Awaitable`[`TypeVar`(`\_NewValueType`)]]) – 

Return type:

[`Future`](#returns.future.Future "returns.future.Future")[`TypeVar`(`\_NewValueType`)]

bind\_io(*function*)[[source]](_modules/returns/future.html#Future.bind_io)[¶](#returns.future.Future.bind_io "Permalink to this definition")

Applies ‘function’ to the result of a previous calculation.

‘function’ should accept a single “normal” (non-container) argument

and return `IO` type object.

```

>>> import anyio

>>> from returns.future import Future

>>> from returns.io import IO

>>> def bindable(x: int) -> IO[int]:

...    return IO(x + 1)

>>> assert anyio.run(

...     Future.from\_value(1).bind\_io(bindable).awaitable,

... ) == IO(2)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`IO`](index.html#returns.io.IO "returns.io.IO")[`TypeVar`(`\_NewValueType`)]]) – 

Return type:

[`Future`](#returns.future.Future "returns.future.Future")[`TypeVar`(`\_NewValueType`)]

*classmethod* do(*expr*)[[source]](_modules/returns/future.html#Future.do)[¶](#returns.future.Future.do "Permalink to this definition")

Allows working with unwrapped values of containers in a safe way.

```

>>> import anyio

>>> from returns.future import Future

>>> from returns.io import IO

>>> async def main() -> bool:

...     return await Future.do(

...         first + second

...         async for first in Future.from\_value(2)

...         async for second in Future.from\_value(3)

...     ) == IO(5)

>>> assert anyio.run(main) is True

```

See [Do Notation](index.html#do-notation) to learn more.

Parameters:

**expr** (`AsyncGenerator`[`TypeVar`(`\_NewValueType`), `None`]) – 

Return type:

[`Future`](#returns.future.Future "returns.future.Future")[`TypeVar`(`\_NewValueType`)]

*classmethod* from\_value(*inner\_value*)[[source]](_modules/returns/future.html#Future.from_value)[¶](#returns.future.Future.from_value "Permalink to this definition")

Allows to create a `Future` from a plain value.

The resulting `Future` will just return the given value

wrapped in [`returns.io.IO`](index.html#returns.io.IO "returns.io.IO") container when awaited.

```

>>> import anyio

>>> from returns.future import Future

>>> from returns.io import IO

>>> async def main() -> bool:

...    return (await Future.from\_value(1)) == IO(1)

>>> assert anyio.run(main) is True

```

Parameters:

**inner\_value** (`TypeVar`(`\_NewValueType`)) – 

Return type:

[`Future`](#returns.future.Future "returns.future.Future")[`TypeVar`(`\_NewValueType`)]

*classmethod* from\_future(*inner\_value*)[[source]](_modules/returns/future.html#Future.from_future)[¶](#returns.future.Future.from_future "Permalink to this definition")

Creates a new `Future` from the existing one.

```

>>> import anyio

>>> from returns.future import Future

>>> from returns.io import IO

>>> future = Future.from\_value(1)

>>> assert anyio.run(Future.from\_future(future).awaitable) == IO(1)

```

Part of the `FutureBasedN` interface.

Parameters:

**inner\_value** ([`Future`](#returns.future.Future "returns.future.Future")[`TypeVar`(`\_NewValueType`)]) – 

Return type:

[`Future`](#returns.future.Future "returns.future.Future")[`TypeVar`(`\_NewValueType`)]

*classmethod* from\_io(*inner\_value*)[[source]](_modules/returns/future.html#Future.from_io)[¶](#returns.future.Future.from_io "Permalink to this definition")

Allows to create a `Future` from `IO` container.

```

>>> import anyio

>>> from returns.future import Future

>>> from returns.io import IO

>>> async def main() -> bool:

...    return (await Future.from\_io(IO(1))) == IO(1)

>>> assert anyio.run(main) is True

```

Parameters:

**inner\_value** ([`IO`](index.html#returns.io.IO "returns.io.IO")[`TypeVar`(`\_NewValueType`)]) – 

Return type:

[`Future`](#returns.future.Future "returns.future.Future")[`TypeVar`(`\_NewValueType`)]

*classmethod* from\_future\_result(*inner\_value*)[[source]](_modules/returns/future.html#Future.from_future_result)[¶](#returns.future.Future.from_future_result "Permalink to this definition")

Creates `Future[Result[a, b]]` instance from `FutureResult[a, b]`.

This method is the inverse of [`from\_typecast()`](#returns.future.FutureResult.from_typecast "returns.future.FutureResult.from_typecast").

```

>>> import anyio

>>> from returns.future import Future, FutureResult

>>> from returns.io import IO

>>> from returns.result import Success

>>> container = Future.from\_future\_result(FutureResult.from\_value(1))

>>> assert anyio.run(container.awaitable) == IO(Success(1))

```

Parameters:

**inner\_value** ([`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]) – 

Return type:

[`Future`](#returns.future.Future "returns.future.Future")[[`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]]

future(*function*)[[source]](_modules/returns/future.html#future)[¶](#returns.future.future "Permalink to this definition")

Decorator to turn a coroutine definition into `Future` container.

```

>>> import anyio

>>> from returns.io import IO

>>> from returns.future import future

>>> @future

... async def test(x: int) -> int:

...     return x + 1

>>> assert anyio.run(test(1).awaitable) == IO(2)

```

Parameters:

**function** (`Callable`[[`ParamSpec`(`\_FuncParams`)], `Coroutine`[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ValueType`, covariant=True)]]) – 

Return type:

`Callable`[[`ParamSpec`(`\_FuncParams`)], [`Future`](#returns.future.Future "returns.future.Future")[`TypeVar`(`\_ValueType`, covariant=True)]]

asyncify(*function*)[[source]](_modules/returns/future.html#asyncify)[¶](#returns.future.asyncify "Permalink to this definition")

Decorator to turn a common function into an asynchronous function.

This decorator is useful for composition with `Future` and

`FutureResult` containers.

Warning

This function will not your sync function **run** like async one.

It will still be a blocking function that looks like async one.

We recommend to only use this decorator with functions

that do not access network or filesystem.

It is only a composition helper, not a transformer.

Usage example:

```

>>> import anyio

>>> from returns.future import asyncify

>>> @asyncify

... def test(x: int) -> int:

...     return x + 1

>>> assert anyio.run(test, 1) == 2

```

Read more about async and sync functions:

<https://journal.stuffwithstuff.com/2015/02/01/what-color-is-your-function/>

Parameters:

**function** (`Callable`[[`ParamSpec`(`\_FuncParams`)], `TypeVar`(`\_ValueType`, covariant=True)]) – 

Return type:

`Callable`[[`ParamSpec`(`\_FuncParams`)], `Coroutine`[`Any`, `Any`, `TypeVar`(`\_ValueType`, covariant=True)]]

*final class* FutureResult(*inner\_value*)[[source]](_modules/returns/future.html#FutureResult)[¶](#returns.future.FutureResult "Permalink to this definition")

Bases: [`BaseContainer`](index.html#returns.primitives.container.BaseContainer "returns.primitives.container.BaseContainer"), [`SupportsKindN`](index.html#returns.primitives.hkt.SupportsKindN "returns.primitives.hkt.SupportsKindN")[[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult"), `\_ValueType`, `\_ErrorType`, `NoReturn`], [`FutureResultBasedN`](index.html#returns.interfaces.specific.future_result.FutureResultBasedN "returns.interfaces.specific.future_result.FutureResultBasedN")[`\_ValueType`, `\_ErrorType`, `NoReturn`]

Container to easily compose `async` functions.

Represents a better abstraction over a simple coroutine.

Is framework, event-loop, and IO-library agnostics.

Works with `asyncio`, `curio`, `trio`, or any other tool.

Internally we use `anyio` to test

that it works as expected for any io stack.

Note that `FutureResult[a, b]` represents a computation

that can fail and returns `IOResult[a, b]` type.

Use `Future[a]` for operations that cannot fail.

This is a `Future` that returns `Result` type.

By providing this utility type we make developers’ lives easier.

`FutureResult` has a lot of composition helpers

to turn complex nested operations into a one function calls.

Tradeoffs

Due to possible performance issues we move all coroutines definitions

to a separate module.

See also

* <https://gcanti.github.io/fp-ts/modules/TaskEither.ts.html>

* <https://zio.dev/docs/overview/overview_basic_concurrency>

Parameters:

**inner\_value** (`Awaitable`[[`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_ErrorType`, covariant=True)]]) – 

*async* awaitable()[[source]](_modules/returns/future.html#FutureResult.awaitable)[¶](#returns.future.FutureResult.awaitable "Permalink to this definition")

Transforms `FutureResult[a, b]` to `Awaitable[IOResult[a, b]]`.

Use this method when you need a real coroutine.

Like for `asyncio.run` calls.

Note, that returned value will be wrapped

in [`returns.io.IOResult`](index.html#returns.io.IOResult "returns.io.IOResult") container.

```

>>> import anyio

>>> from returns.future import FutureResult

>>> from returns.io import IOSuccess

>>> assert anyio.run(

...     FutureResult.from\_value(1).awaitable,

... ) == IOSuccess(1)

```

Return type:

[`IOResult`](index.html#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_ErrorType`, covariant=True)]

swap()[[source]](_modules/returns/future.html#FutureResult.swap)[¶](#returns.future.FutureResult.swap "Permalink to this definition")

Swaps value and error types.

So, values become errors and errors become values.

It is useful when you have to work with errors a lot.

And since we have a lot of `.bind\_` related methods

and only a single `.lash`.

It is easier to work with values than with errors.

```

>>> import anyio

>>> from returns.future import FutureSuccess, FutureFailure

>>> from returns.io import IOSuccess, IOFailure

>>> assert anyio.run(FutureSuccess(1).swap) == IOFailure(1)

>>> assert anyio.run(FutureFailure(1).swap) == IOSuccess(1)

```

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_ValueType`, covariant=True)]

map(*function*)[[source]](_modules/returns/future.html#FutureResult.map)[¶](#returns.future.FutureResult.map "Permalink to this definition")

Applies function to the inner value.

Applies ‘function’ to the contents of the IO instance

and returns a new `FutureResult` object containing the result.

‘function’ should accept a single “normal” (non-container) argument

and return a non-container result.

```

>>> import anyio

>>> from returns.future import FutureResult

>>> from returns.io import IOSuccess, IOFailure

>>> def mappable(x: int) -> int:

...    return x + 1

>>> assert anyio.run(

...     FutureResult.from\_value(1).map(mappable).awaitable,

... ) == IOSuccess(2)

>>> assert anyio.run(

...     FutureResult.from\_failure(1).map(mappable).awaitable,

... ) == IOFailure(1)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `TypeVar`(`\_NewValueType`)]) – 

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]

apply(*container*)[[source]](_modules/returns/future.html#FutureResult.apply)[¶](#returns.future.FutureResult.apply "Permalink to this definition")

Calls a wrapped function in a container on this container.

```

>>> import anyio

>>> from returns.future import FutureResult

>>> from returns.io import IOSuccess, IOFailure

>>> def appliable(x: int) -> int:

...    return x + 1

>>> assert anyio.run(

...     FutureResult.from\_value(1).apply(

...         FutureResult.from\_value(appliable),

...     ).awaitable,

... ) == IOSuccess(2)

>>> assert anyio.run(

...     FutureResult.from\_failure(1).apply(

...         FutureResult.from\_value(appliable),

...     ).awaitable,

... ) == IOFailure(1)

>>> assert anyio.run(

...     FutureResult.from\_value(1).apply(

...         FutureResult.from\_failure(2),

...     ).awaitable,

... ) == IOFailure(2)

>>> assert anyio.run(

...     FutureResult.from\_failure(1).apply(

...         FutureResult.from\_failure(2),

...     ).awaitable,

... ) == IOFailure(1)

```

Parameters:

**container** ([`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult"), `Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `TypeVar`(`\_NewValueType`)], `TypeVar`(`\_ErrorType`, covariant=True), `Any`]) – 

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]

bind(*function*)[[source]](_modules/returns/future.html#FutureResult.bind)[¶](#returns.future.FutureResult.bind "Permalink to this definition")

Applies ‘function’ to the result of a previous calculation.

‘function’ should accept a single “normal” (non-container) argument

and return `Future` type object.

```

>>> import anyio

>>> from returns.future import FutureResult

>>> from returns.io import IOSuccess, IOFailure

>>> def bindable(x: int) -> FutureResult[int, str]:

...    return FutureResult.from\_value(x + 1)

>>> assert anyio.run(

...     FutureResult.from\_value(1).bind(bindable).awaitable,

... ) == IOSuccess(2)

>>> assert anyio.run(

...     FutureResult.from\_failure(1).bind(bindable).awaitable,

... ) == IOFailure(1)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult"), `TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `Any`]]) – 

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]

bind\_future\_result(*function*)[¶](#returns.future.FutureResult.bind_future_result "Permalink to this definition")

Alias for bind method.

Part of the FutureResultBasedN interface.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult"), `TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `Any`]]) – 

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]

bind\_async(*function*)[[source]](_modules/returns/future.html#FutureResult.bind_async)[¶](#returns.future.FutureResult.bind_async "Permalink to this definition")

Composes a container and `async` function returning container.

This function should return a container value.

See [`bind\_awaitable()`](#returns.future.FutureResult.bind_awaitable "returns.future.FutureResult.bind_awaitable")

to bind `async` function that returns a plain value.

```

>>> import anyio

>>> from returns.future import FutureResult

>>> from returns.io import IOSuccess, IOFailure

>>> async def coroutine(x: int) -> FutureResult[str, int]:

...    return FutureResult.from\_value(str(x + 1))

>>> assert anyio.run(

...     FutureResult.from\_value(1).bind\_async(coroutine).awaitable,

... ) == IOSuccess('2')

>>> assert anyio.run(

...     FutureResult.from\_failure(1).bind\_async(coroutine).awaitable,

... ) == IOFailure(1)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `Awaitable`[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult"), `TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `Any`]]]) – 

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]

bind\_async\_future\_result(*function*)[¶](#returns.future.FutureResult.bind_async_future_result "Permalink to this definition")

Alias for bind\_async method.

Part of the FutureResultBasedN interface.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `Awaitable`[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult"), `TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `Any`]]]) – 

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]

bind\_awaitable(*function*)[[source]](_modules/returns/future.html#FutureResult.bind_awaitable)[¶](#returns.future.FutureResult.bind_awaitable "Permalink to this definition")

Allows to compose a container and a regular `async` function.

This function should return plain, non-container value.

See [`bind\_async()`](#returns.future.FutureResult.bind_async "returns.future.FutureResult.bind_async")

to bind `async` function that returns a container.

```

>>> import anyio

>>> from returns.future import FutureResult

>>> from returns.io import IOSuccess, IOFailure

>>> async def coro(x: int) -> int:

...    return x + 1

>>> assert anyio.run(

...     FutureResult.from\_value(1).bind\_awaitable(coro).awaitable,

... ) == IOSuccess(2)

>>> assert anyio.run(

...     FutureResult.from\_failure(1).bind\_awaitable(coro).awaitable,

... ) == IOFailure(1)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `Awaitable`[`TypeVar`(`\_NewValueType`)]]) – 

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]

bind\_result(*function*)[[source]](_modules/returns/future.html#FutureResult.bind_result)[¶](#returns.future.FutureResult.bind_result "Permalink to this definition")

Binds a function returning `Result[a, b]` container.

```

>>> import anyio

>>> from returns.io import IOSuccess, IOFailure

>>> from returns.result import Result, Success

>>> from returns.future import FutureResult

>>> def bind(inner\_value: int) -> Result[int, str]:

...     return Success(inner\_value + 1)

>>> assert anyio.run(

...     FutureResult.from\_value(1).bind\_result(bind).awaitable,

... ) == IOSuccess(2)

>>> assert anyio.run(

...     FutureResult.from\_failure('a').bind\_result(bind).awaitable,

... ) == IOFailure('a')

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]]) – 

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]

bind\_ioresult(*function*)[[source]](_modules/returns/future.html#FutureResult.bind_ioresult)[¶](#returns.future.FutureResult.bind_ioresult "Permalink to this definition")

Binds a function returning `IOResult[a, b]` container.

```

>>> import anyio

>>> from returns.io import IOResult, IOSuccess, IOFailure

>>> from returns.future import FutureResult

>>> def bind(inner\_value: int) -> IOResult[int, str]:

...     return IOSuccess(inner\_value + 1)

>>> assert anyio.run(

...     FutureResult.from\_value(1).bind\_ioresult(bind).awaitable,

... ) == IOSuccess(2)

>>> assert anyio.run(

...     FutureResult.from\_failure('a').bind\_ioresult(bind).awaitable,

... ) == IOFailure('a')

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`IOResult`](index.html#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]]) – 

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]

bind\_io(*function*)[[source]](_modules/returns/future.html#FutureResult.bind_io)[¶](#returns.future.FutureResult.bind_io "Permalink to this definition")

Binds a function returning `IO[a]` container.

```

>>> import anyio

>>> from returns.io import IO, IOSuccess, IOFailure

>>> from returns.future import FutureResult

>>> def bind(inner\_value: int) -> IO[float]:

...     return IO(inner\_value + 0.5)

>>> assert anyio.run(

...     FutureResult.from\_value(1).bind\_io(bind).awaitable,

... ) == IOSuccess(1.5)

>>> assert anyio.run(

...     FutureResult.from\_failure(1).bind\_io(bind).awaitable,

... ) == IOFailure(1)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`IO`](index.html#returns.io.IO "returns.io.IO")[`TypeVar`(`\_NewValueType`)]]) – 

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]

bind\_future(*function*)[[source]](_modules/returns/future.html#FutureResult.bind_future)[¶](#returns.future.FutureResult.bind_future "Permalink to this definition")

Binds a function returning `Future[a]` container.

```

>>> import anyio

>>> from returns.io import IOSuccess, IOFailure

>>> from returns.future import Future, FutureResult

>>> def bind(inner\_value: int) -> Future[float]:

...     return Future.from\_value(inner\_value + 0.5)

>>> assert anyio.run(

...     FutureResult.from\_value(1).bind\_future(bind).awaitable,

... ) == IOSuccess(1.5)

>>> assert anyio.run(

...     FutureResult.from\_failure(1).bind\_future(bind).awaitable,

... ) == IOFailure(1)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`Future`](#returns.future.Future "returns.future.Future")[`TypeVar`(`\_NewValueType`)]]) – 

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]

bind\_async\_future(*function*)[[source]](_modules/returns/future.html#FutureResult.bind_async_future)[¶](#returns.future.FutureResult.bind_async_future "Permalink to this definition")

Composes a container and `async` function returning `Future`.

Similar to [`bind\_future()`](#returns.future.FutureResult.bind_future "returns.future.FutureResult.bind_future")

but works with async functions.

```

>>> import anyio

>>> from returns.future import Future, FutureResult

>>> from returns.io import IOSuccess, IOFailure

>>> async def coroutine(x: int) -> Future[str]:

...    return Future.from\_value(str(x + 1))

>>> assert anyio.run(

...     FutureResult.from\_value(1).bind\_async\_future,

...     coroutine,

... ) == IOSuccess('2')

>>> assert anyio.run(

...     FutureResult.from\_failure(1).bind\_async,

...     coroutine,

... ) == IOFailure(1)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `Awaitable`[[`Future`](#returns.future.Future "returns.future.Future")[`TypeVar`(`\_NewValueType`)]]]) – 

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]

alt(*function*)[[source]](_modules/returns/future.html#FutureResult.alt)[¶](#returns.future.FutureResult.alt "Permalink to this definition")

Composes failed container with a pure function to modify failure.

```

>>> import anyio

>>> from returns.future import FutureResult

>>> from returns.io import IOSuccess, IOFailure

>>> def altable(arg: int) -> int:

...      return arg + 1

>>> assert anyio.run(

...     FutureResult.from\_value(1).alt(altable).awaitable,

... ) == IOSuccess(1)

>>> assert anyio.run(

...     FutureResult.from\_failure(1).alt(altable).awaitable,

... ) == IOFailure(2)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ErrorType`, covariant=True)], `TypeVar`(`\_NewErrorType`)]) – 

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_NewErrorType`)]

lash(*function*)[[source]](_modules/returns/future.html#FutureResult.lash)[¶](#returns.future.FutureResult.lash "Permalink to this definition")

Composes failed container with a function that returns a container.

```

>>> import anyio

>>> from returns.future import FutureResult

>>> from returns.io import IOSuccess

>>> def lashable(x: int) -> FutureResult[int, str]:

...    return FutureResult.from\_value(x + 1)

>>> assert anyio.run(

...     FutureResult.from\_value(1).lash(lashable).awaitable,

... ) == IOSuccess(1)

>>> assert anyio.run(

...     FutureResult.from\_failure(1).lash(lashable).awaitable,

... ) == IOSuccess(2)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ErrorType`, covariant=True)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult"), `TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_NewErrorType`), `Any`]]) – 

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_NewErrorType`)]

compose\_result(*function*)[[source]](_modules/returns/future.html#FutureResult.compose_result)[¶](#returns.future.FutureResult.compose_result "Permalink to this definition")

Composes inner `Result` with `FutureResult` returning function.

Can be useful when you need an access to both states of the result.

```

>>> import anyio

>>> from returns.future import FutureResult

>>> from returns.io import IOSuccess, IOFailure

>>> from returns.result import Result

>>> def count(container: Result[int, int]) -> FutureResult[int, int]:

...     return FutureResult.from\_result(

...         container.map(lambda x: x + 1).alt(abs),

...     )

>>> assert anyio.run(

...    FutureResult.from\_value(1).compose\_result, count,

... ) == IOSuccess(2)

>>> assert anyio.run(

...    FutureResult.from\_failure(-1).compose\_result, count,

... ) == IOFailure(1)

```

Parameters:

**function** (`Callable`[[[`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_ErrorType`, covariant=True)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult"), `TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `Any`]]) – 

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]

*classmethod* do(*expr*)[[source]](_modules/returns/future.html#FutureResult.do)[¶](#returns.future.FutureResult.do "Permalink to this definition")

Allows working with unwrapped values of containers in a safe way.

```

>>> import anyio

>>> from returns.future import FutureResult

>>> from returns.io import IOSuccess, IOFailure

>>> async def success() -> bool:

...     return await FutureResult.do(

...         first + second

...         async for first in FutureResult.from\_value(2)

...         async for second in FutureResult.from\_value(3)

...     ) == IOSuccess(5)

>>> assert anyio.run(success) is True

>>> async def failure() -> bool:

...     return await FutureResult.do(

...         first + second

...         async for first in FutureResult.from\_value(2)

...         async for second in FutureResult.from\_failure(3)

...     ) == IOFailure(3)

>>> assert anyio.run(failure) is True

```

See [Do Notation](index.html#do-notation) to learn more.

Parameters:

**expr** (`AsyncGenerator`[`TypeVar`(`\_NewValueType`), `None`]) – 

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]

*classmethod* from\_typecast(*inner\_value*)[[source]](_modules/returns/future.html#FutureResult.from_typecast)[¶](#returns.future.FutureResult.from_typecast "Permalink to this definition")

Creates `FutureResult[a, b]` from `Future[Result[a, b]]`.

```

>>> import anyio

>>> from returns.io import IOSuccess, IOFailure

>>> from returns.result import Success, Failure

>>> from returns.future import Future, FutureResult

>>> async def main():

...     assert await FutureResult.from\_typecast(

...         Future.from\_value(Success(1)),

...     ) == IOSuccess(1)

...     assert await FutureResult.from\_typecast(

...         Future.from\_value(Failure(1)),

...     ) == IOFailure(1)

>>> anyio.run(main)

```

Parameters:

**inner\_value** ([`Future`](#returns.future.Future "returns.future.Future")[[`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]]) – 

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]

*classmethod* from\_future(*inner\_value*)[[source]](_modules/returns/future.html#FutureResult.from_future)[¶](#returns.future.FutureResult.from_future "Permalink to this definition")

Creates `FutureResult` from successful `Future` value.

```

>>> import anyio

>>> from returns.io import IOSuccess

>>> from returns.future import Future, FutureResult

>>> async def main():

...     assert await FutureResult.from\_future(

...         Future.from\_value(1),

...     ) == IOSuccess(1)

>>> anyio.run(main)

```

Parameters:

**inner\_value** ([`Future`](#returns.future.Future "returns.future.Future")[`TypeVar`(`\_NewValueType`)]) – 

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_NewValueType`), `Any`]

*classmethod* from\_failed\_future(*inner\_value*)[[source]](_modules/returns/future.html#FutureResult.from_failed_future)[¶](#returns.future.FutureResult.from_failed_future "Permalink to this definition")

Creates `FutureResult` from failed `Future` value.

```

>>> import anyio

>>> from returns.io import IOFailure

>>> from returns.future import Future, FutureResult

>>> async def main():

...     assert await FutureResult.from\_failed\_future(

...         Future.from\_value(1),

...     ) == IOFailure(1)

>>> anyio.run(main)

```

Parameters:

**inner\_value** ([`Future`](#returns.future.Future "returns.future.Future")[`TypeVar`(`\_NewErrorType`)]) – 

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`Any`, `TypeVar`(`\_NewErrorType`)]

*classmethod* from\_future\_result(*inner\_value*)[[source]](_modules/returns/future.html#FutureResult.from_future_result)[¶](#returns.future.FutureResult.from_future_result "Permalink to this definition")

Creates new `FutureResult` from existing one.

```

>>> import anyio

>>> from returns.io import IOSuccess

>>> from returns.future import FutureResult

>>> async def main():

...     assert await FutureResult.from\_future\_result(

...         FutureResult.from\_value(1),

...     ) == IOSuccess(1)

>>> anyio.run(main)

```

Part of the `FutureResultLikeN` interface.

Parameters:

**inner\_value** ([`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]) – 

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]

*classmethod* from\_io(*inner\_value*)[[source]](_modules/returns/future.html#FutureResult.from_io)[¶](#returns.future.FutureResult.from_io "Permalink to this definition")

Creates `FutureResult` from successful `IO` value.

```

>>> import anyio

>>> from returns.io import IO, IOSuccess

>>> from returns.future import FutureResult

>>> async def main():

...     assert await FutureResult.from\_io(

...         IO(1),

...     ) == IOSuccess(1)

>>> anyio.run(main)

```

Parameters:

**inner\_value** ([`IO`](index.html#returns.io.IO "returns.io.IO")[`TypeVar`(`\_NewValueType`)]) – 

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_NewValueType`), `Any`]

*classmethod* from\_failed\_io(*inner\_value*)[[source]](_modules/returns/future.html#FutureResult.from_failed_io)[¶](#returns.future.FutureResult.from_failed_io "Permalink to this definition")

Creates `FutureResult` from failed `IO` value.

```

>>> import anyio

>>> from returns.io import IO, IOFailure

>>> from returns.future import FutureResult

>>> async def main():

...     assert await FutureResult.from\_failed\_io(

...         IO(1),

...     ) == IOFailure(1)

>>> anyio.run(main)

```

Parameters:

**inner\_value** ([`IO`](index.html#returns.io.IO "returns.io.IO")[`TypeVar`(`\_NewErrorType`)]) – 

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`Any`, `TypeVar`(`\_NewErrorType`)]

*classmethod* from\_ioresult(*inner\_value*)[[source]](_modules/returns/future.html#FutureResult.from_ioresult)[¶](#returns.future.FutureResult.from_ioresult "Permalink to this definition")

Creates `FutureResult` from `IOResult` value.

```

>>> import anyio

>>> from returns.io import IOSuccess, IOFailure

>>> from returns.future import FutureResult

>>> async def main():

...     assert await FutureResult.from\_ioresult(

...         IOSuccess(1),

...     ) == IOSuccess(1)

...     assert await FutureResult.from\_ioresult(

...         IOFailure(1),

...     ) == IOFailure(1)

>>> anyio.run(main)

```

Parameters:

**inner\_value** ([`IOResult`](index.html#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]) – 

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]

*classmethod* from\_result(*inner\_value*)[[source]](_modules/returns/future.html#FutureResult.from_result)[¶](#returns.future.FutureResult.from_result "Permalink to this definition")

Creates `FutureResult` from `Result` value.

```

>>> import anyio

>>> from returns.io import IOSuccess, IOFailure

>>> from returns.result import Success, Failure

>>> from returns.future import FutureResult

>>> async def main():

...     assert await FutureResult.from\_result(

...         Success(1),

...     ) == IOSuccess(1)

...     assert await FutureResult.from\_result(

...         Failure(1),

...     ) == IOFailure(1)

>>> anyio.run(main)

```

Parameters:

**inner\_value** ([`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]) – 

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]

*classmethod* from\_value(*inner\_value*)[[source]](_modules/returns/future.html#FutureResult.from_value)[¶](#returns.future.FutureResult.from_value "Permalink to this definition")

Creates `FutureResult` from successful value.

```

>>> import anyio

>>> from returns.io import IOSuccess

>>> from returns.future import FutureResult

>>> async def main():

...     assert await FutureResult.from\_value(

...         1,

...     ) == IOSuccess(1)

>>> anyio.run(main)

```

Parameters:

**inner\_value** (`TypeVar`(`\_NewValueType`)) – 

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_NewValueType`), `Any`]

*classmethod* from\_failure(*inner\_value*)[[source]](_modules/returns/future.html#FutureResult.from_failure)[¶](#returns.future.FutureResult.from_failure "Permalink to this definition")

Creates `FutureResult` from failed value.

```

>>> import anyio

>>> from returns.io import IOFailure

>>> from returns.future import FutureResult

>>> async def main():

...     assert await FutureResult.from\_failure(

...         1,

...     ) == IOFailure(1)

>>> anyio.run(main)

```

Parameters:

**inner\_value** (`TypeVar`(`\_NewErrorType`)) – 

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`Any`, `TypeVar`(`\_NewErrorType`)]

FutureSuccess(*inner\_value*)[[source]](_modules/returns/future.html#FutureSuccess)[¶](#returns.future.FutureSuccess "Permalink to this definition")

Public unit function to create successful `FutureResult` objects.

Is the same as [`from\_value()`](#returns.future.FutureResult.from_value "returns.future.FutureResult.from_value").

```

>>> import anyio

>>> from returns.future import FutureResult, FutureSuccess

>>> assert anyio.run(FutureSuccess(1).awaitable) == anyio.run(

...     FutureResult.from\_value(1).awaitable,

... )

```

Parameters:

**inner\_value** (`TypeVar`(`\_NewValueType`)) – 

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_NewValueType`), `Any`]

FutureFailure(*inner\_value*)[[source]](_modules/returns/future.html#FutureFailure)[¶](#returns.future.FutureFailure "Permalink to this definition")

Public unit function to create failed `FutureResult` objects.

Is the same as [`from\_failure()`](#returns.future.FutureResult.from_failure "returns.future.FutureResult.from_failure").

```

>>> import anyio

>>> from returns.future import FutureResult, FutureFailure

>>> assert anyio.run(FutureFailure(1).awaitable) == anyio.run(

...     FutureResult.from\_failure(1).awaitable,

... )

```

Parameters:

**inner\_value** (`TypeVar`(`\_NewErrorType`)) – 

Return type:

[`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`Any`, `TypeVar`(`\_NewErrorType`)]

FutureResultE[¶](#returns.future.FutureResultE "Permalink to this definition")

Alias for a popular case when `Result` has `Exception` as error type.

alias of [`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`\_ValueType`, `Exception`]

future\_safe(*function*)[[source]](_modules/returns/future.html#future_safe)[¶](#returns.future.future_safe "Permalink to this definition")

Decorator to convert exception-throwing coroutine to `FutureResult`.

Should be used with care, since it only catches `Exception` subclasses.

It does not catch `BaseException` subclasses.

If you need to mark sync function as `safe`,

use [`returns.future.future\_safe()`](#returns.future.future_safe "returns.future.future_safe") instead.

This decorator only works with `async` functions. Example:

```

>>> import anyio

>>> from returns.future import future\_safe

>>> from returns.io import IOSuccess, IOResult

>>> @future\_safe

... async def might\_raise(arg: int) -> float:

...     return 1 / arg

...

>>> assert anyio.run(might\_raise(2).awaitable) == IOSuccess(0.5)

>>> assert isinstance(

...     anyio.run(might\_raise(0).awaitable),

...     IOResult.failure\_type,

... )

```

Similar to [`returns.io.impure\_safe()`](index.html#returns.io.impure_safe "returns.io.impure_safe") and [`returns.result.safe()`](index.html#returns.result.safe "returns.result.safe")

decorators, but works with `async` functions.

Parameters:

**function** (`Callable`[[`ParamSpec`(`\_FuncParams`)], `Coroutine`[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ValueType`, covariant=True)]]) – 

Return type:

`Callable`[[`ParamSpec`(`\_FuncParams`)], [`FutureResult`](#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_ValueType`, covariant=True), `Exception`]]

Context[¶](#context "Permalink to this heading")

------------------------------------------------

Dependency injection is a popular software architecture pattern.

It’s main idea is that you provide [Inversion of Control](https://en.wikipedia.org/wiki/Inversion_of_control)

and can pass different things into your logic instead of hardcoding you stuff.

And by doing this you are on your way to achieve [Single Responsibility](https://en.wikipedia.org/wiki/Single_responsibility_principle)

for your functions and objects.

### Using the context[¶](#using-the-context "Permalink to this heading")

A lot of programs we write rely on the context implicitly or explicitly.

We can rely on configuration, env variables, stubs, logical dependencies, etc.

Let’s look at the example.

#### Simple app[¶](#simple-app "Permalink to this heading")

One of the most popular errors Python developers do in `Django`

is that they overuse `settings` object inside the business logic.

This makes your logic framework-oriented

and hard to reason about in large projects.

Because values just pop out of nowhere in a deeply nested functions.

And can be changed from the outside, from the context of your app.

Imagine that you have a `django` based game,

where you award users with points

for each guessed letter in a word (unguessed letters are marked as `'.'`):

```

from django.http import HttpRequest, HttpResponse

from words\_app.logic import calculate\_points

def view(request: HttpRequest) -> HttpResponse:

    user\_word: str = request.POST['word']  # just an example

    points = calculate\_points(user\_word)

    ...  # later you show the result to user somehow

```

```

# Somewhere in your `words\_app/logic.py`:

def calculate\_points(word: str) -> int:

    guessed\_letters\_count = len([letter for letter in word if letter != '.'])

    return \_award\_points\_for\_letters(guessed\_letters\_count)

def \_award\_points\_for\_letters(guessed: int) -> int:

    return 0 if guessed < 5 else guessed  # minimum 6 points possible!

```

Straight and simple!

#### Adding configuration[¶](#adding-configuration "Permalink to this heading")

But, later you decide to make the game more fun:

let’s make the minimal accountable letters threshold

configurable for an extra challenge.

You can just do it directly:

```

def \_award\_points\_for\_letters(guessed: int, threshold: int) -> int:

    return 0 if guessed < threshold else guessed

```

And now your code won’t simply type-check.

Because that’s how our caller looks like:

```

def calculate\_points(word: str) -> int:

    guessed\_letters\_count = len([letter for letter in word if letter != '.'])

    return \_award\_points\_for\_letters(guessed\_letters\_count)

```

To fix this `calculate\_points` function

(and all other upper caller functions)

will have to accept `threshold: int`

as a parameter and pass it to `\_award\_points\_for\_letters`.

Imagine that your large project has multiple

things to configure in multiple functions.

What a mess it would be!

Ok, you can directly use `django.settings` (or similar)

in your `\_award\_points\_for\_letters` function.

And ruin your pure logic with framework-specific details. That’s ugly!

#### Explicitly reling on context[¶](#explicitly-reling-on-context "Permalink to this heading")

We have learned that this tiny change showed us

that it is not so easy to rely on implicit app context.

And instead of passing parameters for all callstack

or using dirty framework specific magic

you can use `RequiresContext` container.

That was built just for this case.

Let’s see how our code changes:

```

from django.conf import settings

from django.http import HttpRequest, HttpResponse

from words\_app.logic import calculate\_points

def view(request: HttpRequest) -> HttpResponse:

    user\_word: str = request.POST['word']  # just an example

    points = calculate\_points(user\_words)(settings)  # passing the dependencies

    ...  # later you show the result to user somehow

```

```

# Somewhere in your `words\_app/logic.py`:

from typing import Protocol

from returns.context import RequiresContext

class \_Deps(Protocol):  # we rely on abstractions, not direct values or types

    WORD\_THRESHOLD: int

def calculate\_points(word: str) -> RequiresContext[int, \_Deps]:

    guessed\_letters\_count = len([letter for letter in word if letter != '.'])

    return \_award\_points\_for\_letters(guessed\_letters\_count)

def \_award\_points\_for\_letters(guessed: int) -> RequiresContext[int, \_Deps]:

    return RequiresContext(

        lambda deps: 0 if guessed < deps.WORD\_THRESHOLD else guessed,

    )

```

And now you can pass your dependencies in a really direct and explicit way.

#### ask[¶](#ask "Permalink to this heading")

Let’s try to configure how we mark our unguessed letters

(previously unguessed letters were marked as `'.'`).

Let’s say, we want to change this to be `\_`.

How can we do that with our existing function?

```

def calculate\_points(word: str) -> RequiresContext[int, \_Deps]:

    guessed\_letters\_count = len([letter for letter in word if letter != '.'])

    return \_award\_points\_for\_letters(guessed\_letters\_count)

```

We are already using `RequiresContext`,

but its dependencies are just hidden from us!

We have a special helper for this case: `.ask()`,

which returns us current dependencies.

The only thing we need to is to properly

annotate the type for our case: `RequiresContext[int, \_Deps].ask()`

Sadly, currently `mypy` is not able to infer the dependency type

out of the context and we need to explicitly provide it.

Let’s see the final result:

```

from returns.context import RequiresContext

class \_Deps(Protocol):  # we rely on abstractions, not direct values or types

    WORD\_THRESHOLD: int

    UNGUESSED\_CHAR: str

def calculate\_points(word: str) -> RequiresContext[int, \_Deps]:

    def factory(deps: \_Deps) -> RequiresContext[int, \_Deps]:

        guessed\_letters\_count = len([

            letter for letter in word if letter != deps.UNGUESSED\_CHAR

        ])

        return \_award\_points\_for\_letters(guessed\_letters\_count)

    return RequiresContext[int, \_Deps].ask().bind(factory)

```

And now we access the current context from any place in our callstack.

Isn’t it convenient?

Warning

`RequiresContext` and similar types are not recursion safe.

If you would have nesting of more than `sys.getrecursionlimit()`

you will end up with `RecursionError`.

Will this ever happen to you? Probably not.

### RequiresContext container[¶](#requirescontext-container "Permalink to this heading")

The concept behind

[`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")

container is really simple.

It is a container around `Callable[[EnvType], ReturnType]` function.

By its definition it works with pure functions that never fails.

It can be illustrated as a simple nested function:

```

>>> from typing import Callable

>>> def first(limit: int) -> Callable[[str], bool]:

...     def inner(deps: str) -> bool:

...         return len(deps) > limit

...     return inner

>>> assert first(2)('abc')  # first(limit)(deps)

>>> assert not first(5)('abc')  # first(limit)(deps)

```

That’s basically enough to make dependency injection possible.

But how would you compose `first` function?

Let’s say with the following function:

```

>>> def bool\_to\_str(arg: bool) -> str:

...     return 'ok' if arg else 'nope'

```

It would be hard, knowing that it returns another

function to be called later when the context is known.

We can wrap it in `RequiresContext` container to allow better composition!

```

>>> from returns.context import RequiresContext

>>> def first(limit: int) -> RequiresContext[bool, str]:

...     def inner(deps: str) -> bool:

...         return len(deps) > limit

...     return RequiresContext(inner)  # wrapping function here!

>>> assert first(1).map(bool\_to\_str)('abc') == 'ok'

>>> assert first(5).map(bool\_to\_str)('abc') == 'nope'

```

There’s how execution flows:

 graph LR

 F1["first(1)"] --> F2["RequiresContext(inner)"]

 F2 --> F3

 F3["container('abc')"] --> F4["True"]

 F4 --> F5

 F5["bool\_to\_str(True)"] --> F6["'ok'"]

 

RequiresContext execution flow.[¶](#id3 "Permalink to this image")

The rule is: the dependencies are injected at the very last moment in time.

And then normal logical execution happens.

### RequiresContextResult container[¶](#requirescontextresult-container "Permalink to this heading")

[`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult") container

is a combination of `RequiresContext[Result[a, b], env]`.

Which means that it is a wrapper around pure function that might fail.

We also added a lot of useful methods for this container,

so you can work easily with it:

* [`bind\_result()`](#returns.context.requires_context_result.RequiresContextResult.bind_result "returns.context.requires_context_result.RequiresContextResult.bind_result")

allows to bind functions that return `Result` with just one call

* [`bind\_context()`](#returns.context.requires_context_result.RequiresContextResult.bind_context "returns.context.requires_context_result.RequiresContextResult.bind_context")

allows to bind functions that return `RequiresContext` easily

* There are also several useful constructors from any possible type

Use it when you work with pure context-related functions that might fail.

### RequiresContextIOResult container[¶](#requirescontextioresult-container "Permalink to this heading")

[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult") container

is a combination of `RequiresContext[IOResult[a, b], env]`.

Which means that it is a wrapper around impure function that might fail.

We also added a lot of useful methods for this container,

so you can work easily with it:

* [`bind\_result()`](#returns.context.requires_context_ioresult.RequiresContextIOResult.bind_result "returns.context.requires_context_ioresult.RequiresContextIOResult.bind_result")

allows to bind functions that return `Result` with just one call

* [`bind\_io()`](#returns.context.requires_context_ioresult.RequiresContextIOResult.bind_io "returns.context.requires_context_ioresult.RequiresContextIOResult.bind_io")

allows to bind functions that return `IO` with just one call

* [`bind\_ioresult()`](#returns.context.requires_context_ioresult.RequiresContextIOResult.bind_ioresult "returns.context.requires_context_ioresult.RequiresContextIOResult.bind_ioresult")

allows to bind functions that return `IOResult` with just one call

* [`bind\_context()`](#returns.context.requires_context_ioresult.RequiresContextIOResult.bind_context "returns.context.requires_context_ioresult.RequiresContextIOResult.bind_context")

allows to bind functions that return `RequiresContext` easily

* [`bind\_context\_result()`](#returns.context.requires_context_ioresult.RequiresContextIOResult.bind_context_result "returns.context.requires_context_ioresult.RequiresContextIOResult.bind_context_result")

allows to bind functions that return `RequiresContextResult` easily

* There are also several useful constructors from any possible type

Use it when you work with impure context-related functions that might fail.

This is basically **the main type** that is going to be used in most apps.

### RequiresContextFutureResult container[¶](#requirescontextfutureresult-container "Permalink to this heading")

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult") container

is a combination of `RequiresContext[FutureResult[a, b], env]`.

Which means that it is a wrapper around impure async function that might fail.

Here’s how it should be used:

```

 1from typing import Final, Sequence, cast

 2

 3import anyio  # you would need to `pip install anyio`

 4import httpx  # you would need to `pip install httpx`

 5from typing\_extensions import TypedDict

 6

 7from returns.context import RequiresContextFutureResultE

 8from returns.functions import tap

 9from returns.future import FutureResultE, future\_safe

10from returns.iterables import Fold

11from returns.pipeline import managed

12from returns.result import ResultE, safe

13

14\_URL: Final = 'https://jsonplaceholder.typicode.com/posts/{0}'

15

16

17class \_Post(TypedDict):

18    id: int

19    user\_id: int

20    title: str

21    body: str

22

23

24def \_close(

25    client: httpx.AsyncClient,

26    raw\_value: ResultE[Sequence[str]],

27) -> FutureResultE[None]:

28    return future\_safe(client.aclose)()

29

30

31def \_fetch\_post(

32    post\_id: int,

33) -> RequiresContextFutureResultE[\_Post, httpx.AsyncClient]:

34    context: RequiresContextFutureResultE[

35        httpx.AsyncClient,

36        httpx.AsyncClient,

37    ] = RequiresContextFutureResultE.ask()

38

39    return context.bind\_future\_result(

40        lambda client: future\_safe(client.get)(\_URL.format(post\_id)),

41    ).bind\_result(

42        safe(tap(httpx.Response.raise\_for\_status)),

43    ).map(

44        lambda response: cast(\_Post, response.json()),  # or validate it

45    )

46

47

48def \_show\_titles(

49    number\_of\_posts: int,

50) -> RequiresContextFutureResultE[Sequence[str], httpx.AsyncClient]:

51    def factory(post: \_Post) -> str:

52        return post['title']

53

54    titles = [

55        # Notice how easily we compose async and sync functions:

56        \_fetch\_post(post\_id).map(factory)

57        # TODO: try `for post\_id in (2, 1, 0):` to see how errors work

58        for post\_id in range(1, number\_of\_posts + 1)

59    ]

60    return Fold.collect(titles, RequiresContextFutureResultE.from\_value(()))

61

62

63if \_\_name\_\_ == '\_\_main\_\_':

64    # Let's fetch 3 titles of posts one-by-one, but with async client,

65    # because we want to highlight `managed` in this example:

66    managed\_httpx = managed(\_show\_titles(3), \_close)

67    future\_result = managed\_httpx(

68        FutureResultE.from\_value(httpx.AsyncClient(timeout=5)),

69    )

70    print(anyio.run(future\_result.awaitable))  # noqa: WPS421

71    # <IOResult: <Success: (

72    # 'sunt aut facere repellat provident occaecati ...',

73    # 'qui est esse',

74    # 'ea molestias quasi exercitationem repellat qui ipsa sit aut',

75    # )>>

```

This example illustrates the whole point of our actions: writing

sync code that executes asynchronously without any magic at all!

We also added a lot of useful methods for this container,

so you can work easily with it.

These methods are identical with `RequiresContextIOResult`:

* [`bind\_result()`](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind_result "returns.context.requires_context_future_result.RequiresContextFutureResult.bind_result")

allows to bind functions that return `Result` with just one call

* [`bind\_io()`](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind_io "returns.context.requires_context_future_result.RequiresContextFutureResult.bind_io")

allows to bind functions that return `IO` with just one call

* [`bind\_ioresult()`](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind_ioresult "returns.context.requires_context_future_result.RequiresContextFutureResult.bind_ioresult")

allows to bind functions that return `IOResult` with just one call

* [`bind\_future\_result()`](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind_future_result "returns.context.requires_context_future_result.RequiresContextFutureResult.bind_future_result")

allows to bind functions that return `FutureResult` with just one call

* [`bind\_context()`](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind_context "returns.context.requires_context_future_result.RequiresContextFutureResult.bind_context")

allows to bind functions that return `RequiresContext` easily

* [`bind\_context\_result()`](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind_context_result "returns.context.requires_context_future_result.RequiresContextFutureResult.bind_context_result")

allows to bind functions that return `RequiresContextResult` easily

There are new ones:

* [`bind\_future()`](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind_future "returns.context.requires_context_future_result.RequiresContextFutureResult.bind_future")

allows to bind functions that return `Future` container

* [`bind\_future\_result()`](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind_future_result "returns.context.requires_context_future_result.RequiresContextFutureResult.bind_future_result")

allows to bind functions that return `FutureResult` container

* [`bind\_async\_future()`](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind_async_future "returns.context.requires_context_future_result.RequiresContextFutureResult.bind_async_future")

allows to bind async functions that return `Future` container

* [`bind\_async\_future\_result()`](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind_async_future_result "returns.context.requires_context_future_result.RequiresContextFutureResult.bind_async_future_result")

allows to bind async functions that return `FutureResult` container

* [`bind\_context\_ioresult()`](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind_context_ioresult "returns.context.requires_context_future_result.RequiresContextFutureResult.bind_context_ioresult")

allows to bind functions that return `RequiresContextIOResult`

* [`bind\_async()`](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind_async "returns.context.requires_context_future_result.RequiresContextFutureResult.bind_async")

allows to bind async functions

that return `RequiresContextFutureResult` container

* [`bind\_awaitable()`](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind_awaitable "returns.context.requires_context_future_result.RequiresContextFutureResult.bind_awaitable")

allows to bind async function that return raw values

Use it when you work with impure context-related functions that might fail.

This is basically **the main type** that is going to be used in most apps.

### Aliases[¶](#aliases "Permalink to this heading")

There are several useful aliases for `RequiresContext`

and friends with some common values:

* [`Reader`](#returns.context.requires_context.Reader "returns.context.requires_context.Reader")

is an alias for `RequiresContext[...]` to save you some typing.

Uses `Reader` because it is a native name for this concept from Haskell.

* [`RequiresContextResultE`](#returns.context.requires_context_result.RequiresContextResultE "returns.context.requires_context_result.RequiresContextResultE")

is an alias for `RequiresContextResult[..., Exception]`,

just use it when you want to work with `RequiresContextResult` containers

that use exceptions as error type.

It is named `ResultE` because it is `ResultException`

and `ResultError` at the same time.

* [`ReaderResult`](#returns.context.requires_context_result.ReaderResult "returns.context.requires_context_result.ReaderResult")

is an alias for `RequiresContextResult[...]` to save you some typing.

* [`ReaderResultE`](#returns.context.requires_context_result.ReaderResultE "returns.context.requires_context_result.ReaderResultE")

is an alias for `RequiresContextResult[..., Exception]`

* [`RequiresContextIOResultE`](#returns.context.requires_context_ioresult.RequiresContextIOResultE "returns.context.requires_context_ioresult.RequiresContextIOResultE")

is an alias for `RequiresContextIOResult[..., Exception]`

* [`ReaderIOResult`](#returns.context.requires_context_ioresult.ReaderIOResult "returns.context.requires_context_ioresult.ReaderIOResult")

is an alias for `RequiresContextIOResult[...]` to save you some typing.

* [`ReaderIOResultE`](#returns.context.requires_context_ioresult.ReaderIOResultE "returns.context.requires_context_ioresult.ReaderIOResultE")

is an alias for `RequiresContextIOResult[..., Exception]`

* [`RequiresContextFutureResultE`](#returns.context.requires_context_future_result.RequiresContextFutureResultE "returns.context.requires_context_future_result.RequiresContextFutureResultE")

is an alias for `RequiresContextFutureResult[..., Exception]`

* [`ReaderFutureResult`](#returns.context.requires_context_future_result.ReaderFutureResult "returns.context.requires_context_future_result.ReaderFutureResult")

is an alias for `RequiresContextFutureResult[...]` to save you some typing.

* [`ReaderFutureResultE`](#returns.context.requires_context_future_result.ReaderFutureResultE "returns.context.requires_context_future_result.ReaderFutureResultE")

is an alias for `RequiresContextFutureResult[..., Exception]`

### FAQ[¶](#faq "Permalink to this heading")

#### How to create unit objects?[¶](#how-to-create-unit-objects "Permalink to this heading")

`RequiresContext` requires you to use one of the following methods:

* `from\_value` when you have a raw value

* `from\_requires\_context\_result` when you have `RequiresContextResult`

* `from\_requires\_context\_ioresult` when you have `RequiresContextIOResult`

`RequiresContextResult` requires you to use one of the following methods:

* `from\_value` when you want to mark some raw value as a `Success`

* `from\_failure` when you want to mark some raw value as a `Failure`

* `from\_result` when you already have `Result` container

* `from\_context` when you have successful `RequiresContext`

* `from\_failed\_context` when you have failed `RequiresContext`

* `from\_typecast` when you have `RequiresContext[..., Result]`

`RequiresContextIOResult` requires you to use one of the following methods:

* `from\_value` when you want to mark some raw value as a `Success`

* `from\_failure` when you want to mark some raw value as a `Failure`

* `from\_result` when you already have `Result` container

* `from\_io` when you have successful `IO` container

* `from\_failed\_io` when you have failed `IO` container

* `from\_ioresult` when you already have `IOResult` container

* `from\_context` when you have successful `RequiresContext` container

* `from\_failed\_context` when you have failed `RequiresContext` container

* `from\_result\_context` when you have `RequiresContextResult` container

* `from\_typecast` when you have `RequiresContext[..., IOResult]`

`RequiresContextFutureResult` requires

you to use one of the following methods:

* `from\_value` when you want to mark some raw value as a `Success`

* `from\_failure` when you want to mark some raw value as a `Failure`

* `from\_result` when you already have `Result` container

* `from\_io` when you have successful `IO` container

* `from\_failed\_io` when you have failed `IO` container

* `from\_ioresult` when you already have `IOResult` container

* `from\_future` when you already have successful `Future` container

* `from\_failed\_future` when you already have failed `Future` container

* `from\_future\_result` when you already have `FutureResult` container

* `from\_context` when you have successful `RequiresContext`

* `from\_failed\_context` when you have failed `RequiresContext`

* `from\_result\_context` when you have `RequiresContextResult` container

* `from\_ioresult\_context` when you have `RequiresContextIOResult` container

* `from\_typecast` when you have `RequiresContext[..., IOResult]`

#### How can I access dependencies inside the context?[¶](#how-can-i-access-dependencies-inside-the-context "Permalink to this heading")

Use `.ask()` method!

See [this guide](#ask).

#### RequiresContext looks like a decorator with arguments[¶](#requirescontext-looks-like-a-decorator-with-arguments "Permalink to this heading")

Yes, this container might remind a traditional decorator with arguments,

let see an example:

```

>>> def example(print\_result: bool):

...     def decorator(function):

...         def factory(\*args, \*\*kwargs):

...             original = function(\*args, \*\*kwargs)

...             if print\_result:

...                 print(original)

...             return original

...         return factory

...     return decorator

```

And it can be used like so:

```

>>> @example(print\_result=True)

... def my\_function(first: int, second: int) -> int:

...     return first + second

>>> assert my\_function(2, 3) == 5

5

```

We can model the similar idea with `RequiresContext`:

```

>>> from returns.context import RequiresContext

>>> def my\_function(first: int, second: int) -> RequiresContext[int, bool]:

...     def factory(print\_result: bool) -> int:

...         original = first + second

...         if print\_result:

...             print(original)

...         return original

...     return RequiresContext(factory)

>>> assert my\_function(2, 3)(False) == 5

>>> assert my\_function(2, 3)(True) == 5

5

```

As you can see,

it is easier to change the behaviour of a function with `RequiresContext`.

While decorator with arguments glues values to a function forever.

Decide when you need which behaviour carefully.

#### Why can’t we use RequiresContext[Result, e] instead of RequiresContextResult?[¶](#why-cant-we-use-requirescontext-result-e-instead-of-requirescontextresult "Permalink to this heading")

We actually can! But, it is harder to write.

And `RequiresContextResult` is actually

the very same thing as `RequiresContext[Result, e]`, but has nicer API:

```

x: RequiresContext[Result[int, str], int]

x.map(lambda result: result.map(lambda number: number + 1))

# Is the same as:

y: RequiresContextResult[int, str, int]

y.map(lambda number: number + 1)

```

The second one looks better, doesn’t it?

The same applies for `RequiresContextIOResult`

and `RequiresContextFutureResult` as well.

#### Why do I have to use explicit type annotation for ask method?[¶](#why-do-i-have-to-use-explicit-type-annotation-for-ask-method "Permalink to this heading")

Because `mypy` cannot possibly know the type of current context.

This is hard even for a plugin.

So, using this technique is better:

```

from returns.context import RequiresContext

def some\_context(\*args, \*\*kwargs) -> RequiresContext[str, int]:

    def factory(deps: int) -> RequiresContext[str, int]:

        ...

    return RequiresContext[str, int].ask().bind(factory)

```

#### What is the difference between DI and RequiresContext?[¶](#what-is-the-difference-between-di-and-requirescontext "Permalink to this heading")

Dependency Injection pattern and

[Inversion of Control](https://en.wikipedia.org/wiki/Inversion_of_control)

principle forms a lot of ideas and tooling

that do pretty much the same as `RequiresContext` container.

What is the difference? Why do we need each of them?

Let’s find out!

Tools like [dependencies](https://github.com/proofit404/dependencies)

or [punq](https://github.com/bobthemighty/punq)

tries to:

1. Inspect (by name or type respectively)

function or class that needs dependencies

2. Build the required dependency tree from the source

defined in the service container

There are other tools like `inject` that also invades

your code with `@inject` decorator.

`RequiresContext` works completely different.

It respects your code and does not try to inspect in any manner.

It also does not care about building dependencies at all.

All it does is: provides simple API to compose functions

that need additional context (or dependencies) to run.

You can even use them together: `RequiresContext` will pass dependencies

built by `punq` (or any other tool of your choice)

as a `deps` parameter to `RequiresContext` instance.

When to use which? Let’s dig into it!

* `RequiresContext` offers explicit context passing

for the whole function stack inside your program.

This means two things: you will have to pass it through all your code and

use it everywhere inside your program explicitly,

when you need to access the environment and dependencies

* Traditional `DI` allows to leave a lot

of code unaware of dependency injection.

Because you don’t have to maintain the context everywhere.

You just need to adjust your API to meet the dependency injector requirements.

On the other hand, you lose explicitness here.

So when to use `RequiresContext`?

1. When you write pure functional code

2. When you want to know which code relies on context and which is free from it,

`RequiresContext` makes this explicit and typed

3. When you rely on types inside your program

4. When you want to rely on functions rather than magic

When not to use `RequiresContext` and use traditional DI?

1. When you already have a lot of code written in a different approach:

in OOP and/or imperative styles

2. When you need to pass dependencies into a very deep level of your call stack

implicitly (without modifying the whole stack), this is called magic

3. When you not rely on types for dependencies.

There are cases when DI is made by names or tags

Here’s an example that might give you a better understanding of how

`RequiresContext` is used on real and rather big projects:

```

from typing import Callable, Dict, Protocol, final

from returns.io import IOResultE

from returns.context import ReaderIOResultE

class \_SyncPermissionsDeps(Protocol):

    fetch\_metadata: Callable[[], IOResultE['Metadata']]

    get\_user\_permissions: Callable[['Metadata'], Dict[int, str]]  # pure

    update\_bi\_permissions: Callable[[Dict[int, str]], IOResultE['Payload']]

def sync\_permissions() -> ReaderIOResultE[\_SyncPermissionsDeps, 'Payload']:

 """

 This functions runs a scheduled task once a day.

 It syncs permissions from the metadata storage to our BI system.

 """

    def factory(deps: \_SyncPermissionsDeps) -> IOResultE['Payload']:

        return deps.fetch\_metadata().map(

            deps.get\_user\_permissions,

        ).bind\_ioresult(

            deps.update\_bi\_permissions,

        )

    return ReaderIOResult(factory)

```

And then it is called like so:

```

# tasks.py

from celery import shared\_task

from returns.functions import raise\_exception

from logic.usecases.sync\_permissions import sync\_permissions

from infrastructure.implemented import Container

from infrastructure.services import bi

from infrastructure.repositories import db

@shared\_task(autoretry\_for=(ConnectionError,), max\_retries=3)

def queue\_sync\_permissions():

    # Building the container with dependencies to pass it into the context.

    # We also make sure that we don't forget to raise internal exceptions

    # and trigger celery retries.

    return sync\_permissions().alt(raise\_exception)(Container(

        fetch\_metadata=db.select\_user\_metadata,

        get\_user\_permissions=bi.permissions\_from\_user,

        update\_bi\_permissions=bi.put\_user\_permissions,

    ))

```

### Further reading[¶](#further-reading "Permalink to this heading")

* [Enforcing Single Responsibility Principle in Python](https://sobolevn.me/2019/03/enforcing-srp)

* [Typed functional Dependency Injection in Python](https://sobolevn.me/2020/02/typed-functional-dependency-injection)

* [Three-Useful-Monads: Reader](https://github.com/dbrattli/OSlash/wiki/Three-Useful-Monads#the-reader-monad)

* [Getting started with fp-ts: Reader](https://dev.to/gcanti/getting-started-with-fp-ts-reader-1ie5)

* [Reader & Constructor-based Dependency Injection in Scala - friend or foe?](https://softwaremill.com/reader-monad-constructor-dependency-injection-friend-or-foe/)

### API Reference[¶](#api-reference "Permalink to this heading")

#### RequiresContext[¶](#requirescontext "Permalink to this heading")

 classDiagram

 BaseContainer <|-- RequiresContext

 ReaderBased2 <|-- RequiresContext

 SupportsKindN <|-- RequiresContext

 

NoDeps *= typing.Any*[¶](#returns.context.requires_context.NoDeps "Permalink to this definition")

Sometimes `RequiresContext` and other similar types might be used with

no explicit dependencies so we need to have this type alias for Any.

*final class* RequiresContext(*inner\_value*)[[source]](_modules/returns/context/requires_context.html#RequiresContext)[¶](#returns.context.requires_context.RequiresContext "Permalink to this definition")

Bases: [`BaseContainer`](index.html#returns.primitives.container.BaseContainer "returns.primitives.container.BaseContainer"), [`SupportsKindN`](index.html#returns.primitives.hkt.SupportsKindN "returns.primitives.hkt.SupportsKindN")[[`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext"), `\_ReturnType`, `\_EnvType`, `NoReturn`], [`ReaderBased2`](index.html#returns.interfaces.specific.reader.ReaderBased2 "returns.interfaces.specific.reader.ReaderBased2")[`\_ReturnType`, `\_EnvType`]

The `RequiresContext` container.

It’s main purpose is to wrap some specific function

and to provide tools to compose other functions around it

without actually calling it.

The `RequiresContext` container passes the state

you want to share between functions.

Functions may read that state, but can’t change it.

The `RequiresContext` container

lets us access shared immutable state within a specific context.

It can be used for lazy evaluation and typed dependency injection.

`RequiresContext` is used with functions that never fail.

If you want to use `RequiresContext` with returns `Result`

then consider using `RequiresContextResult` instead.

Note

This container does not wrap ANY value. It wraps only functions.

You won’t be able to supply arbitrary types!

See also

* <https://dev.to/gcanti/getting-started-with-fp-ts-reader-1ie5>

* <https://en.wikipedia.org/wiki/Lazy_evaluation>

* <https://bit.ly/2R8l4WK>

Parameters:

**inner\_value** (`Callable`[[`TypeVar`(`\_EnvType`, contravariant=True)], `TypeVar`(`\_ReturnType`, covariant=True)]) – 

no\_args*: ClassVar[NoDeps]* *= <object object>*[¶](#returns.context.requires_context.RequiresContext.no_args "Permalink to this definition")

A convenient placeholder to call methods created by .from\_value():

map(*function*)[[source]](_modules/returns/context/requires_context.html#RequiresContext.map)[¶](#returns.context.requires_context.RequiresContext.map "Permalink to this definition")

Allows to compose functions inside the wrapped container.

Here’s how it works:

```

>>> from returns.context import RequiresContext

>>> def first(lg: bool) -> RequiresContext[int, float]:

...     # `deps` has `float` type here:

...     return RequiresContext(

...         lambda deps: deps if lg else -deps,

...     )

>>> assert first(True).map(lambda number: number \* 10)(2.5) == 25.0

>>> assert first(False).map(lambda number: number \* 10)(0.1) -1.0

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ReturnType`, covariant=True)], `TypeVar`(`\_NewReturnType`)]) – 

Return type:

[`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[`TypeVar`(`\_NewReturnType`), `TypeVar`(`\_EnvType`, contravariant=True)]

apply(*container*)[[source]](_modules/returns/context/requires_context.html#RequiresContext.apply)[¶](#returns.context.requires_context.RequiresContext.apply "Permalink to this definition")

Calls a wrapped function in a container on this container.

```

>>> from returns.context import RequiresContext

>>> assert RequiresContext.from\_value('a').apply(

...    RequiresContext.from\_value(lambda inner: inner + 'b')

... )(...) == 'ab'

```

Parameters:

**container** ([`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext"), `Callable`[[`TypeVar`(`\_ReturnType`, covariant=True)], `TypeVar`(`\_NewReturnType`)], `TypeVar`(`\_EnvType`, contravariant=True), `Any`]) – 

Return type:

[`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[`TypeVar`(`\_NewReturnType`), `TypeVar`(`\_EnvType`, contravariant=True)]

bind(*function*)[[source]](_modules/returns/context/requires_context.html#RequiresContext.bind)[¶](#returns.context.requires_context.RequiresContext.bind "Permalink to this definition")

Composes a container with a function returning another container.

This is useful when you do several computations that rely on the

same context.

```

>>> from returns.context import RequiresContext

>>> def first(lg: bool) -> RequiresContext[int, float]:

...     # `deps` has `float` type here:

...     return RequiresContext(

...         lambda deps: deps if lg else -deps,

...     )

>>> def second(number: int) -> RequiresContext[str, float]:

...     # `deps` has `float` type here:

...     return RequiresContext(

...         lambda deps: '>=' if number >= deps else '<',

...     )

>>> assert first(True).bind(second)(1) == '>='

>>> assert first(False).bind(second)(2) == '<'

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ReturnType`, covariant=True)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext"), `TypeVar`(`\_NewReturnType`), `TypeVar`(`\_EnvType`, contravariant=True), `Any`]]) – 

Return type:

[`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[`TypeVar`(`\_NewReturnType`), `TypeVar`(`\_EnvType`, contravariant=True)]

bind\_context(*function*)[¶](#returns.context.requires_context.RequiresContext.bind_context "Permalink to this definition")

Alias for bind\_context method, it is the same as bind here.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ReturnType`, covariant=True)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext"), `TypeVar`(`\_NewReturnType`), `TypeVar`(`\_EnvType`, contravariant=True), `Any`]]) – 

Return type:

[`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[`TypeVar`(`\_NewReturnType`), `TypeVar`(`\_EnvType`, contravariant=True)]

modify\_env(*function*)[[source]](_modules/returns/context/requires_context.html#RequiresContext.modify_env)[¶](#returns.context.requires_context.RequiresContext.modify_env "Permalink to this definition")

Allows to modify the environment type.

```

>>> from returns.context import RequiresContext

>>> def mul(arg: int) -> RequiresContext[float, int]:

...     return RequiresContext(lambda deps: arg \* deps)

>>> assert mul(3).modify\_env(int)('2') == 6

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_NewEnvType`)], `TypeVar`(`\_EnvType`, contravariant=True)]) – 

Return type:

[`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[`TypeVar`(`\_ReturnType`, covariant=True), `TypeVar`(`\_NewEnvType`)]

*classmethod* ask()[[source]](_modules/returns/context/requires_context.html#RequiresContext.ask)[¶](#returns.context.requires_context.RequiresContext.ask "Permalink to this definition")

Get current context to use the dependencies.

It is a common scenario when you need to use the environment.

For example, you want to do some context-related computation,

but you don’t have the context instance at your disposal.

That’s where `.ask()` becomes useful!

```

>>> from typing\_extensions import TypedDict

>>> class Deps(TypedDict):

...     message: str

>>> def first(lg: bool) -> RequiresContext[int, Deps]:

...     # `deps` has `Deps` type here:

...     return RequiresContext(

...         lambda deps: deps['message'] if lg else 'error',

...     )

>>> def second(text: str) -> RequiresContext[int, Deps]:

...     return first(len(text) > 3)

>>> assert second('abc')({'message': 'ok'}) == 'error'

>>> assert second('abcd')({'message': 'ok'}) == 'ok'

```

And now imagine that you have to change this `3` limit.

And you want to be able to set it via environment as well.

Ok, let’s fix it with the power of `RequiresContext.ask()`!

```

>>> from typing\_extensions import TypedDict

>>> class Deps(TypedDict):

...     message: str

...     limit: int   # note this new field!

>>> def new\_first(lg: bool) -> RequiresContext[int, Deps]:

...     # `deps` has `Deps` type here:

...     return RequiresContext(

...         lambda deps: deps['message'] if lg else 'err',

...     )

>>> def new\_second(text: str) -> RequiresContext[int, Deps]:

...     return RequiresContext[int, Deps].ask().bind(

...         lambda deps: new\_first(len(text) > deps.get('limit', 3)),

...     )

>>> assert new\_second('abc')({'message': 'ok', 'limit': 2}) == 'ok'

>>> assert new\_second('abcd')({'message': 'ok'}) == 'ok'

>>> assert new\_second('abcd')({'message': 'ok', 'limit': 5}) == 'err'

```

That’s how `ask` works.

This class contains methods that require

to explicitly set type annotations. Why?

Because it is impossible to figure out the type without them.

So, here’s how you should use them:

```

RequiresContext[int, Dict[str, str]].ask()

```

Otherwise, your `.ask()` method

will return `RequiresContext[<nothing>, <nothing>]`,

which is unusable:

```

env = RequiresContext.ask()

env(some\_deps)

```

And `mypy` will warn you: `error: Need type annotation for '...'`

:rtype: [`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[`TypeVar`(`\_EnvType`, contravariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

See also

* <https://dev.to/gcanti/getting-started-with-fp-ts-reader-1ie5>

*classmethod* from\_value(*inner\_value*)[[source]](_modules/returns/context/requires_context.html#RequiresContext.from_value)[¶](#returns.context.requires_context.RequiresContext.from_value "Permalink to this definition")

Used to return some specific value from the container.

Consider this method as some kind of factory.

Passed value will be a return type.

Make sure to use [`no\_args`](#returns.context.requires_context.RequiresContext.no_args "returns.context.requires_context.RequiresContext.no_args")

for getting the unit value.

```

>>> from returns.context import RequiresContext

>>> unit = RequiresContext.from\_value(5)

>>> assert unit(RequiresContext.no\_args) == 5

```

Might be used with or without direct type hint.

Parameters:

**inner\_value** (`TypeVar`(`\_FirstType`)) – 

Return type:

[`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[`TypeVar`(`\_FirstType`), `Any`]

*classmethod* from\_context(*inner\_value*)[[source]](_modules/returns/context/requires_context.html#RequiresContext.from_context)[¶](#returns.context.requires_context.RequiresContext.from_context "Permalink to this definition")

Used to create new containers from existing ones.

Used as a part of `ReaderBased2` interface.

```

>>> from returns.context import RequiresContext

>>> unit = RequiresContext.from\_value(5)

>>> assert RequiresContext.from\_context(unit)(...) == unit(...)

```

Parameters:

**inner\_value** ([`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[`TypeVar`(`\_NewReturnType`), `TypeVar`(`\_NewEnvType`)]) – 

Return type:

[`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[`TypeVar`(`\_NewReturnType`), `TypeVar`(`\_NewEnvType`)]

*classmethod* from\_requires\_context\_result(*inner\_value*)[[source]](_modules/returns/context/requires_context.html#RequiresContext.from_requires_context_result)[¶](#returns.context.requires_context.RequiresContext.from_requires_context_result "Permalink to this definition")

Typecasts `RequiresContextResult` to `RequiresContext` instance.

Breaks `RequiresContextResult[a, b, e]`

into `RequiresContext[Result[a, b], e]`.

```

>>> from returns.context import RequiresContext

>>> from returns.context import RequiresContextResult

>>> from returns.result import Success

>>> assert RequiresContext.from\_requires\_context\_result(

...    RequiresContextResult.from\_value(1),

... )(...) == Success(1)

```

Can be reverted with `RequiresContextResult.from\_typecast`.

Parameters:

**inner\_value** ([`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`TypeVar`(`\_ValueType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]) – 

Return type:

[`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[[`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_ValueType`), `TypeVar`(`\_ErrorType`)], `TypeVar`(`\_EnvType`, contravariant=True)]

*classmethod* from\_requires\_context\_ioresult(*inner\_value*)[[source]](_modules/returns/context/requires_context.html#RequiresContext.from_requires_context_ioresult)[¶](#returns.context.requires_context.RequiresContext.from_requires_context_ioresult "Permalink to this definition")

Typecasts `RequiresContextIOResult` to `RequiresContext` instance.

Breaks `RequiresContextIOResult[a, b, e]`

into `RequiresContext[IOResult[a, b], e]`.

```

>>> from returns.context import RequiresContext

>>> from returns.context import RequiresContextIOResult

>>> from returns.io import IOSuccess

>>> assert RequiresContext.from\_requires\_context\_ioresult(

...    RequiresContextIOResult.from\_value(1),

... )(...) == IOSuccess(1)

```

Can be reverted with `RequiresContextIOResult.from\_typecast`.

Parameters:

**inner\_value** ([`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_ValueType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]) – 

Return type:

[`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[[`IOResult`](index.html#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_ValueType`), `TypeVar`(`\_ErrorType`)], `TypeVar`(`\_EnvType`, contravariant=True)]

*classmethod* from\_requires\_context\_future\_result(*inner\_value*)[[source]](_modules/returns/context/requires_context.html#RequiresContext.from_requires_context_future_result)[¶](#returns.context.requires_context.RequiresContext.from_requires_context_future_result "Permalink to this definition")

Typecasts `RequiresContextIOResult` to `RequiresContext` instance.

Breaks `RequiresContextIOResult[a, b, e]`

into `RequiresContext[IOResult[a, b], e]`.

```

>>> import anyio

>>> from returns.context import RequiresContext

>>> from returns.context import RequiresContextFutureResult

>>> from returns.io import IOSuccess

>>> container = RequiresContext.from\_requires\_context\_future\_result(

...    RequiresContextFutureResult.from\_value(1),

... )

>>> assert anyio.run(

...     container, RequiresContext.no\_args,

... ) == IOSuccess(1)

```

Can be reverted with `RequiresContextFutureResult.from\_typecast`.

Parameters:

**inner\_value** ([`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_ValueType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]) – 

Return type:

[`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[[`FutureResult`](index.html#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_ValueType`), `TypeVar`(`\_ErrorType`)], `TypeVar`(`\_EnvType`, contravariant=True)]

Reader[¶](#returns.context.requires_context.Reader "Permalink to this definition")

Sometimes RequiresContext is too long to type.

Parameters:

**inner\_value** (`Callable`[[`TypeVar`(`\_EnvType`, contravariant=True)], `TypeVar`(`\_ReturnType`, covariant=True)]) – 

#### RequiresContextResult[¶](#requirescontextresult "Permalink to this heading")

 classDiagram

 BaseContainer <|-- RequiresContextResult

 ReaderResultBasedN <|-- RequiresContextResult

 SupportsKindN <|-- RequiresContextResult

 

*final class* RequiresContextResult(*inner\_value*)[[source]](_modules/returns/context/requires_context_result.html#RequiresContextResult)[¶](#returns.context.requires_context_result.RequiresContextResult "Permalink to this definition")

Bases: [`BaseContainer`](index.html#returns.primitives.container.BaseContainer "returns.primitives.container.BaseContainer"), [`SupportsKindN`](index.html#returns.primitives.hkt.SupportsKindN "returns.primitives.hkt.SupportsKindN")[[`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult"), `\_ValueType`, `\_ErrorType`, `\_EnvType`], [`ReaderResultBasedN`](index.html#returns.interfaces.specific.reader_result.ReaderResultBasedN "returns.interfaces.specific.reader_result.ReaderResultBasedN")[`\_ValueType`, `\_ErrorType`, `\_EnvType`]

The `RequiresContextResult` combinator.

See [`returns.context.requires\_context.RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext") for more docs.

This is just a handy wrapper around `RequiresContext[Result[a, b], env]`

which represents a context-dependent pure operation

that might fail and return [`returns.result.Result`](index.html#returns.result.Result "returns.result.Result").

It has several important differences from the regular `Result` classes.

It does not have `Success` and `Failure` subclasses.

Because, the computation is not yet performed.

And we cannot know the type in advance.

So, this is a thin wrapper, without any changes in logic.

Why do we need this wrapper? That’s just for better usability!

```

>>> from returns.context import RequiresContext

>>> from returns.result import Success, Result

>>> def function(arg: int) -> Result[int, str]:

...      return Success(arg + 1)

>>> # Without wrapper:

>>> assert RequiresContext.from\_value(Success(1)).map(

...     lambda result: result.bind(function),

... )(...) == Success(2)

>>> # With wrapper:

>>> assert RequiresContextResult.from\_value(1).bind\_result(

...     function,

... )(...) == Success(2)

```

This way `RequiresContextResult` allows to simply work with:

* raw values and pure functions

* `RequiresContext` values and pure functions returning it

* `Result` and functions returning it

Important implementation details

Due it is meaning, `RequiresContextResult`

cannot have `Success` and `Failure` subclasses.

We only have just one type. That’s by design.

Different converters are also not supported for this type.

Use converters inside the `RequiresContext` context, not outside.

See also

* <https://dev.to/gcanti/getting-started-with-fp-ts-reader-1ie5>

* <https://en.wikipedia.org/wiki/Lazy_evaluation>

* <https://bit.ly/2R8l4WK>

* <https://bit.ly/2RwP4fp>

Parameters:

**inner\_value** (`Callable`[[`TypeVar`(`\_EnvType`, contravariant=True)], [`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_ErrorType`, covariant=True)]]) – 

no\_args*: ClassVar[NoDeps]* *= <object object>*[¶](#returns.context.requires_context_result.RequiresContextResult.no_args "Permalink to this definition")

A convenient placeholder to call methods created by .from\_value().

swap()[[source]](_modules/returns/context/requires_context_result.html#RequiresContextResult.swap)[¶](#returns.context.requires_context_result.RequiresContextResult.swap "Permalink to this definition")

Swaps value and error types.

So, values become errors and errors become values.

It is useful when you have to work with errors a lot.

And since we have a lot of `.bind\_` related methods

and only a single `.lash` - it is easier to work with values.

```

>>> from returns.context import RequiresContextResult

>>> from returns.result import Failure, Success

>>> success = RequiresContextResult.from\_value(1)

>>> failure = RequiresContextResult.from\_failure(1)

>>> assert success.swap()(...) == Failure(1)

>>> assert failure.swap()(...) == Success(1)

```

Return type:

[`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

map(*function*)[[source]](_modules/returns/context/requires_context_result.html#RequiresContextResult.map)[¶](#returns.context.requires_context_result.RequiresContextResult.map "Permalink to this definition")

Composes successful container with a pure function.

```

>>> from returns.context import RequiresContextResult

>>> from returns.result import Success, Failure

>>> assert RequiresContextResult.from\_value(1).map(

...     lambda x: x + 1,

... )(...) == Success(2)

>>> assert RequiresContextResult.from\_failure(1).map(

...     lambda x: x + 1,

... )(...) == Failure(1)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `TypeVar`(`\_NewValueType`)]) – 

Return type:

[`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

apply(*container*)[[source]](_modules/returns/context/requires_context_result.html#RequiresContextResult.apply)[¶](#returns.context.requires_context_result.RequiresContextResult.apply "Permalink to this definition")

Calls a wrapped function in a container on this container.

```

>>> from returns.context import RequiresContextResult

>>> from returns.result import Success, Failure, Result

>>> def transform(arg: str) -> str:

...     return arg + 'b'

>>> assert RequiresContextResult.from\_value('a').apply(

...    RequiresContextResult.from\_value(transform),

... )(...) == Success('ab')

>>> assert RequiresContextResult.from\_failure('a').apply(

...    RequiresContextResult.from\_value(transform),

... )(...) == Failure('a')

>>> assert isinstance(RequiresContextResult.from\_value('a').apply(

...    RequiresContextResult.from\_failure(transform),

... )(...), Result.failure\_type) is True

```

Parameters:

**container** ([`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult"), `Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `TypeVar`(`\_NewValueType`)], `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]) – 

Return type:

[`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

bind(*function*)[[source]](_modules/returns/context/requires_context_result.html#RequiresContextResult.bind)[¶](#returns.context.requires_context_result.RequiresContextResult.bind "Permalink to this definition")

Composes this container with a function returning the same type.

```

>>> from returns.context import RequiresContextResult

>>> from returns.result import Success, Failure

>>> def first(lg: bool) -> RequiresContextResult[int, int, float]:

...     # `deps` has `float` type here:

...     return RequiresContextResult(

...         lambda deps: Success(deps) if lg else Failure(-deps),

...     )

>>> def second(

...     number: int,

... ) -> RequiresContextResult[str, int, float]:

...     # `deps` has `float` type here:

...     return RequiresContextResult(

...         lambda deps: Success('>=' if number >= deps else '<'),

...     )

>>> assert first(True).bind(second)(1) == Success('>=')

>>> assert first(False).bind(second)(2) == Failure(-2)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult"), `TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]]) – 

Return type:

[`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

bind\_context\_result(*function*)[¶](#returns.context.requires_context_result.RequiresContextResult.bind_context_result "Permalink to this definition")

Alias for bind\_context\_result method, it is the same as bind here.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult"), `TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]]) – 

Return type:

[`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

bind\_result(*function*)[[source]](_modules/returns/context/requires_context_result.html#RequiresContextResult.bind_result)[¶](#returns.context.requires_context_result.RequiresContextResult.bind_result "Permalink to this definition")

Binds `Result` returning function to current container.

```

>>> from returns.context import RequiresContextResult

>>> from returns.result import Success, Failure, Result

>>> def function(num: int) -> Result[str, int]:

...     return Success(num + 1) if num > 0 else Failure('<0')

>>> assert RequiresContextResult.from\_value(1).bind\_result(

...     function,

... )(RequiresContextResult.no\_args) == Success(2)

>>> assert RequiresContextResult.from\_value(0).bind\_result(

...     function,

... )(RequiresContextResult.no\_args) == Failure('<0')

>>> assert RequiresContextResult.from\_failure(':(').bind\_result(

...     function,

... )(RequiresContextResult.no\_args) == Failure(':(')

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]]) – 

Return type:

[`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

bind\_context(*function*)[[source]](_modules/returns/context/requires_context_result.html#RequiresContextResult.bind_context)[¶](#returns.context.requires_context_result.RequiresContextResult.bind_context "Permalink to this definition")

Binds `RequiresContext` returning function to current container.

```

>>> from returns.context import RequiresContext

>>> from returns.result import Success, Failure

>>> def function(arg: int) -> RequiresContext[int, str]:

...     return RequiresContext(lambda deps: len(deps) + arg)

>>> assert function(2)('abc') == 5

>>> assert RequiresContextResult.from\_value(2).bind\_context(

...     function,

... )('abc') == Success(5)

>>> assert RequiresContextResult.from\_failure(2).bind\_context(

...     function,

... )('abc') == Failure(2)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_EnvType`, contravariant=True)]]) – 

Return type:

[`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

alt(*function*)[[source]](_modules/returns/context/requires_context_result.html#RequiresContextResult.alt)[¶](#returns.context.requires_context_result.RequiresContextResult.alt "Permalink to this definition")

Composes failed container with a pure function.

```

>>> from returns.context import RequiresContextResult

>>> from returns.result import Success, Failure

>>> assert RequiresContextResult.from\_value(1).alt(

...     lambda x: x + 1,

... )(...) == Success(1)

>>> assert RequiresContextResult.from\_failure(1).alt(

...     lambda x: x + 1,

... )(...) == Failure(2)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ErrorType`, covariant=True)], `TypeVar`(`\_NewErrorType`)]) – 

Return type:

[`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_NewErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]

lash(*function*)[[source]](_modules/returns/context/requires_context_result.html#RequiresContextResult.lash)[¶](#returns.context.requires_context_result.RequiresContextResult.lash "Permalink to this definition")

Composes this container with a function returning the same type.

```

>>> from returns.context import RequiresContextResult

>>> from returns.result import Success, Failure

>>> def lashable(arg: str) -> RequiresContextResult[str, str, str]:

...      if len(arg) > 1:

...          return RequiresContextResult(

...              lambda deps: Success(deps + arg),

...          )

...      return RequiresContextResult(

...          lambda deps: Failure(arg + deps),

...      )

>>> assert RequiresContextResult.from\_value('a').lash(

...     lashable,

... )('c') == Success('a')

>>> assert RequiresContextResult.from\_failure('a').lash(

...     lashable,

... )('c') == Failure('ac')

>>> assert RequiresContextResult.from\_failure('aa').lash(

...     lashable,

... )('b') == Success('baa')

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ErrorType`, covariant=True)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult"), `TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_NewErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]]) – 

Return type:

[`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_NewErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]

modify\_env(*function*)[[source]](_modules/returns/context/requires_context_result.html#RequiresContextResult.modify_env)[¶](#returns.context.requires_context_result.RequiresContextResult.modify_env "Permalink to this definition")

Allows to modify the environment type.

```

>>> from returns.context import RequiresContextResultE

>>> from returns.result import Success, safe

>>> def div(arg: int) -> RequiresContextResultE[float, int]:

...     return RequiresContextResultE(

...         safe(lambda deps: arg / deps),

...     )

>>> assert div(3).modify\_env(int)('2') == Success(1.5)

>>> assert div(3).modify\_env(int)('0').failure()

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_NewEnvType`)], `TypeVar`(`\_EnvType`, contravariant=True)]) – 

Return type:

[`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_NewEnvType`)]

*classmethod* ask()[[source]](_modules/returns/context/requires_context_result.html#RequiresContextResult.ask)[¶](#returns.context.requires_context_result.RequiresContextResult.ask "Permalink to this definition")

Is used to get the current dependencies inside the call stack.

Similar to [`returns.context.requires\_context.RequiresContext.ask()`](#returns.context.requires_context.RequiresContext.ask "returns.context.requires_context.RequiresContext.ask"),

but returns `Result` instead of a regular value.

Please, refer to the docs there to learn how to use it.

One important note that is worth duplicating here:

you might need to provide `\_EnvType` explicitly,

so `mypy` will know about it statically.

```

>>> from returns.context import RequiresContextResultE

>>> from returns.result import Success

>>> assert RequiresContextResultE[int, int].ask().map(

...    str,

... )(1) == Success('1')

```

Return type:

[`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`TypeVar`(`\_EnvType`, contravariant=True), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

*classmethod* from\_result(*inner\_value*)[[source]](_modules/returns/context/requires_context_result.html#RequiresContextResult.from_result)[¶](#returns.context.requires_context_result.RequiresContextResult.from_result "Permalink to this definition")

Creates new container with `Result` as a unit value.

```

>>> from returns.context import RequiresContextResult

>>> from returns.result import Success, Failure

>>> deps = RequiresContextResult.no\_args

>>> assert RequiresContextResult.from\_result(

...    Success(1),

... )(deps) == Success(1)

>>> assert RequiresContextResult.from\_result(

...    Failure(1),

... )(deps) == Failure(1)

```

Parameters:

**inner\_value** ([`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]) – 

Return type:

[`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`), `Any`]

*classmethod* from\_typecast(*inner\_value*)[[source]](_modules/returns/context/requires_context_result.html#RequiresContextResult.from_typecast)[¶](#returns.context.requires_context_result.RequiresContextResult.from_typecast "Permalink to this definition")

You might end up with `RequiresContext[Result[...]]` as a value.

This method is designed to turn it into `RequiresContextResult`.

It will save all the typing information.

It is just more useful!

```

>>> from returns.context import RequiresContext

>>> from returns.result import Success, Failure

>>> assert RequiresContextResult.from\_typecast(

...     RequiresContext.from\_value(Success(1)),

... )(RequiresContextResult.no\_args) == Success(1)

>>> assert RequiresContextResult.from\_typecast(

...     RequiresContext.from\_value(Failure(1)),

... )(RequiresContextResult.no\_args) == Failure(1)

```

Parameters:

**inner\_value** ([`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[[`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)], `TypeVar`(`\_EnvType`, contravariant=True)]) – 

Return type:

[`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]

*classmethod* from\_context(*inner\_value*)[[source]](_modules/returns/context/requires_context_result.html#RequiresContextResult.from_context)[¶](#returns.context.requires_context_result.RequiresContextResult.from_context "Permalink to this definition")

Creates new container from `RequiresContext` as a success unit.

```

>>> from returns.context import RequiresContext

>>> from returns.result import Success

>>> assert RequiresContextResult.from\_context(

...     RequiresContext.from\_value(1),

... )(...) == Success(1)

```

Parameters:

**inner\_value** ([`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewEnvType`)]) – 

Return type:

[`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`TypeVar`(`\_NewValueType`), `Any`, `TypeVar`(`\_NewEnvType`)]

*classmethod* from\_failed\_context(*inner\_value*)[[source]](_modules/returns/context/requires_context_result.html#RequiresContextResult.from_failed_context)[¶](#returns.context.requires_context_result.RequiresContextResult.from_failed_context "Permalink to this definition")

Creates new container from `RequiresContext` as a failure unit.

```

>>> from returns.context import RequiresContext

>>> from returns.result import Failure

>>> assert RequiresContextResult.from\_failed\_context(

...     RequiresContext.from\_value(1),

... )(...) == Failure(1)

```

Parameters:

**inner\_value** ([`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewEnvType`)]) – 

Return type:

[`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`Any`, `TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewEnvType`)]

*classmethod* from\_result\_context(*inner\_value*)[[source]](_modules/returns/context/requires_context_result.html#RequiresContextResult.from_result_context)[¶](#returns.context.requires_context_result.RequiresContextResult.from_result_context "Permalink to this definition")

Creates `RequiresContextResult` from another instance of it.

```

>>> from returns.context import ReaderResult

>>> from returns.result import Success, Failure

>>> assert ReaderResult.from\_result\_context(

...     ReaderResult.from\_value(1),

... )(...) == Success(1)

>>> assert ReaderResult.from\_result\_context(

...     ReaderResult.from\_failure(1),

... )(...) == Failure(1)

```

Parameters:

**inner\_value** ([`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`), `TypeVar`(`\_NewEnvType`)]) – 

Return type:

[`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`), `TypeVar`(`\_NewEnvType`)]

*classmethod* from\_value(*inner\_value*)[[source]](_modules/returns/context/requires_context_result.html#RequiresContextResult.from_value)[¶](#returns.context.requires_context_result.RequiresContextResult.from_value "Permalink to this definition")

Creates new container with `Success(inner\_value)` as a unit value.

```

>>> from returns.context import RequiresContextResult

>>> from returns.result import Success

>>> assert RequiresContextResult.from\_value(1)(...) == Success(1)

```

Parameters:

**inner\_value** (`TypeVar`(`\_FirstType`)) – 

Return type:

[`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`TypeVar`(`\_FirstType`), `Any`, `Any`]

*classmethod* from\_failure(*inner\_value*)[[source]](_modules/returns/context/requires_context_result.html#RequiresContextResult.from_failure)[¶](#returns.context.requires_context_result.RequiresContextResult.from_failure "Permalink to this definition")

Creates new container with `Failure(inner\_value)` as a unit value.

```

>>> from returns.context import RequiresContextResult

>>> from returns.result import Failure

>>> assert RequiresContextResult.from\_failure(1)(...) == Failure(1)

```

Parameters:

**inner\_value** (`TypeVar`(`\_FirstType`)) – 

Return type:

[`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`Any`, `TypeVar`(`\_FirstType`), `Any`]

RequiresContextResultE[¶](#returns.context.requires_context_result.RequiresContextResultE "Permalink to this definition")

Alias for a popular case when `Result` has `Exception` as error type.

alias of [`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`\_ValueType`, `Exception`, `\_EnvType`]

ReaderResult[¶](#returns.context.requires_context_result.ReaderResult "Permalink to this definition")

Alias to save you some typing. Uses original name from Haskell.

Parameters:

**inner\_value** (`Callable`[[`TypeVar`(`\_EnvType`, contravariant=True)], [`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_ErrorType`, covariant=True)]]) – 

ReaderResultE[¶](#returns.context.requires_context_result.ReaderResultE "Permalink to this definition")

Alias to save you some typing. Has `Exception` as error type.

alias of [`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`\_ValueType`, `Exception`, `\_EnvType`]

#### RequiresContextIOResult[¶](#requirescontextioresult "Permalink to this heading")

 classDiagram

 BaseContainer <|-- RequiresContextIOResult

 ReaderIOResultBasedN <|-- RequiresContextIOResult

 SupportsKindN <|-- RequiresContextIOResult

 

*final class* RequiresContextIOResult(*inner\_value*)[[source]](_modules/returns/context/requires_context_ioresult.html#RequiresContextIOResult)[¶](#returns.context.requires_context_ioresult.RequiresContextIOResult "Permalink to this definition")

Bases: [`BaseContainer`](index.html#returns.primitives.container.BaseContainer "returns.primitives.container.BaseContainer"), [`SupportsKindN`](index.html#returns.primitives.hkt.SupportsKindN "returns.primitives.hkt.SupportsKindN")[[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult"), `\_ValueType`, `\_ErrorType`, `\_EnvType`], [`ReaderIOResultBasedN`](index.html#returns.interfaces.specific.reader_ioresult.ReaderIOResultBasedN "returns.interfaces.specific.reader_ioresult.ReaderIOResultBasedN")[`\_ValueType`, `\_ErrorType`, `\_EnvType`]

The `RequiresContextIOResult` combinator.

See [`returns.context.requires\_context.RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")

and [`returns.context.requires\_context\_result.RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")

for more docs.

This is just a handy wrapper around

`RequiresContext[IOResult[a, b], env]`

which represents a context-dependent impure operation that might fail.

It has several important differences from the regular `Result` classes.

It does not have `Success` and `Failure` subclasses.

Because, the computation is not yet performed.

And we cannot know the type in advance.

So, this is a thin wrapper, without any changes in logic.

Why do we need this wrapper? That’s just for better usability!

```

>>> from returns.context import RequiresContext

>>> from returns.io import IOSuccess, IOResult

>>> def function(arg: int) -> IOResult[int, str]:

...      return IOSuccess(arg + 1)

>>> # Without wrapper:

>>> assert RequiresContext.from\_value(IOSuccess(1)).map(

...     lambda ioresult: ioresult.bind(function),

... )(...) == IOSuccess(2)

>>> # With wrapper:

>>> assert RequiresContextIOResult.from\_value(1).bind\_ioresult(

...     function,

... )(...) == IOSuccess(2)

```

This way `RequiresContextIOResult` allows to simply work with:

* raw values and pure functions

* `RequiresContext` values and pure functions returning it

* `RequiresContextResult` values and pure functions returning it

* `Result` and pure functions returning it

* `IOResult` and functions returning it

* other `RequiresContextIOResult` related functions and values

This is a complex type for complex tasks!

Important implementation details

Due it is meaning, `RequiresContextIOResult`

cannot have `Success` and `Failure` subclasses.

We only have just one type. That’s by design.

Different converters are also not supported for this type.

Use converters inside the `RequiresContext` context, not outside.

See also

* <https://dev.to/gcanti/getting-started-with-fp-ts-reader-1ie5>

* <https://en.wikipedia.org/wiki/Lazy_evaluation>

* <https://bit.ly/2R8l4WK>

* <https://bit.ly/2RwP4fp>

Parameters:

**inner\_value** (`Callable`[[`TypeVar`(`\_EnvType`, contravariant=True)], [`IOResult`](index.html#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_ErrorType`)]]) – 

no\_args*: ClassVar[NoDeps]* *= <object object>*[¶](#returns.context.requires_context_ioresult.RequiresContextIOResult.no_args "Permalink to this definition")

A convenient placeholder to call methods created by .from\_value().

swap()[[source]](_modules/returns/context/requires_context_ioresult.html#RequiresContextIOResult.swap)[¶](#returns.context.requires_context_ioresult.RequiresContextIOResult.swap "Permalink to this definition")

Swaps value and error types.

So, values become errors and errors become values.

It is useful when you have to work with errors a lot.

And since we have a lot of `.bind\_` related methods

and only a single `.lash` - it is easier to work with values.

```

>>> from returns.context import RequiresContextIOResult

>>> from returns.io import IOSuccess, IOFailure

>>> success = RequiresContextIOResult.from\_value(1)

>>> failure = RequiresContextIOResult.from\_failure(1)

>>> assert success.swap()(...) == IOFailure(1)

>>> assert failure.swap()(...) == IOSuccess(1)

```

Return type:

[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_ErrorType`), `TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

map(*function*)[[source]](_modules/returns/context/requires_context_ioresult.html#RequiresContextIOResult.map)[¶](#returns.context.requires_context_ioresult.RequiresContextIOResult.map "Permalink to this definition")

Composes successful container with a pure function.

```

>>> from returns.context import RequiresContextIOResult

>>> from returns.io import IOSuccess, IOFailure

>>> assert RequiresContextIOResult.from\_value(1).map(

...     lambda x: x + 1,

... )(...) == IOSuccess(2)

>>> assert RequiresContextIOResult.from\_failure(1).map(

...     lambda x: x + 1,

... )(...) == IOFailure(1)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `TypeVar`(`\_NewValueType`)]) – 

Return type:

[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]

apply(*container*)[[source]](_modules/returns/context/requires_context_ioresult.html#RequiresContextIOResult.apply)[¶](#returns.context.requires_context_ioresult.RequiresContextIOResult.apply "Permalink to this definition")

Calls a wrapped function in a container on this container.

```

>>> from returns.context import RequiresContextIOResult

>>> from returns.io import IOSuccess, IOFailure

>>> def transform(arg: str) -> str:

...     return arg + 'b'

>>> assert RequiresContextIOResult.from\_value('a').apply(

...    RequiresContextIOResult.from\_value(transform),

... )(...) == IOSuccess('ab')

>>> assert RequiresContextIOResult.from\_value('a').apply(

...    RequiresContextIOResult.from\_failure(1),

... )(...) == IOFailure(1)

>>> assert RequiresContextIOResult.from\_failure('a').apply(

...    RequiresContextIOResult.from\_value(transform),

... )(...) == IOFailure('a')

>>> assert RequiresContextIOResult.from\_failure('a').apply(

...    RequiresContextIOResult.from\_failure('b'),

... )(...) == IOFailure('a')

```

Parameters:

**container** ([`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult"), `Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `TypeVar`(`\_NewValueType`)], `TypeVar`(`\_ErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]) – 

Return type:

[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]

bind(*function*)[[source]](_modules/returns/context/requires_context_ioresult.html#RequiresContextIOResult.bind)[¶](#returns.context.requires_context_ioresult.RequiresContextIOResult.bind "Permalink to this definition")

Composes this container with a function returning the same type.

```

>>> from returns.context import RequiresContextIOResult

>>> from returns.io import IOSuccess, IOFailure

>>> def first(lg: bool) -> RequiresContextIOResult[int, int, float]:

...     # `deps` has `float` type here:

...     return RequiresContextIOResult(

...         lambda deps: IOSuccess(deps) if lg else IOFailure(-deps),

...     )

>>> def second(

...     number: int,

... ) -> RequiresContextIOResult[str, int, float]:

...     # `deps` has `float` type here:

...     return RequiresContextIOResult(

...         lambda deps: IOSuccess('>=' if number >= deps else '<'),

...     )

>>> assert first(True).bind(second)(1) == IOSuccess('>=')

>>> assert first(False).bind(second)(2) == IOFailure(-2)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult"), `TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]]) – 

Return type:

[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]

bind\_context\_ioresult(*function*)[¶](#returns.context.requires_context_ioresult.RequiresContextIOResult.bind_context_ioresult "Permalink to this definition")

Alias for bind\_context\_ioresult method, it is the same as bind here.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult"), `TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]]) – 

Return type:

[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]

bind\_result(*function*)[[source]](_modules/returns/context/requires_context_ioresult.html#RequiresContextIOResult.bind_result)[¶](#returns.context.requires_context_ioresult.RequiresContextIOResult.bind_result "Permalink to this definition")

Binds `Result` returning function to the current container.

```

>>> from returns.context import RequiresContextIOResult

>>> from returns.result import Success, Failure, Result

>>> from returns.io import IOSuccess, IOFailure

>>> def function(num: int) -> Result[int, str]:

...     return Success(num + 1) if num > 0 else Failure('<0')

>>> assert RequiresContextIOResult.from\_value(1).bind\_result(

...     function,

... )(RequiresContextIOResult.no\_args) == IOSuccess(2)

>>> assert RequiresContextIOResult.from\_value(0).bind\_result(

...     function,

... )(RequiresContextIOResult.no\_args) == IOFailure('<0')

>>> assert RequiresContextIOResult.from\_failure(':(').bind\_result(

...     function,

... )(RequiresContextIOResult.no\_args) == IOFailure(':(')

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`)]]) – 

Return type:

[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]

bind\_context(*function*)[[source]](_modules/returns/context/requires_context_ioresult.html#RequiresContextIOResult.bind_context)[¶](#returns.context.requires_context_ioresult.RequiresContextIOResult.bind_context "Permalink to this definition")

Binds `RequiresContext` returning function to current container.

```

>>> from returns.context import RequiresContext

>>> from returns.io import IOSuccess, IOFailure

>>> def function(arg: int) -> RequiresContext[int, str]:

...     return RequiresContext(lambda deps: len(deps) + arg)

>>> assert function(2)('abc') == 5

>>> assert RequiresContextIOResult.from\_value(2).bind\_context(

...     function,

... )('abc') == IOSuccess(5)

>>> assert RequiresContextIOResult.from\_failure(2).bind\_context(

...     function,

... )('abc') == IOFailure(2)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_EnvType`, contravariant=True)]]) – 

Return type:

[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]

bind\_context\_result(*function*)[[source]](_modules/returns/context/requires_context_ioresult.html#RequiresContextIOResult.bind_context_result)[¶](#returns.context.requires_context_ioresult.RequiresContextIOResult.bind_context_result "Permalink to this definition")

Binds `RequiresContextResult` returning function to the current one.

```

>>> from returns.context import RequiresContextResult

>>> from returns.io import IOSuccess, IOFailure

>>> from returns.result import Success, Failure

>>> def function(arg: int) -> RequiresContextResult[int, int, str]:

...     if arg > 0:

...         return RequiresContextResult(

...             lambda deps: Success(len(deps) + arg),

...         )

...     return RequiresContextResult(

...         lambda deps: Failure(len(deps) + arg),

...     )

>>> assert function(2)('abc') == Success(5)

>>> assert function(-1)('abc') == Failure(2)

>>> assert RequiresContextIOResult.from\_value(

...    2,

... ).bind\_context\_result(

...     function,

... )('abc') == IOSuccess(5)

>>> assert RequiresContextIOResult.from\_value(

...    -1,

... ).bind\_context\_result(

...     function,

... )('abc') == IOFailure(2)

>>> assert RequiresContextIOResult.from\_failure(

...    2,

... ).bind\_context\_result(

...     function,

... )('abc') == IOFailure(2)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]]) – 

Return type:

[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]

bind\_io(*function*)[[source]](_modules/returns/context/requires_context_ioresult.html#RequiresContextIOResult.bind_io)[¶](#returns.context.requires_context_ioresult.RequiresContextIOResult.bind_io "Permalink to this definition")

Binds `IO` returning function to the current container.

```

>>> from returns.context import RequiresContextIOResult

>>> from returns.io import IO, IOSuccess, IOFailure

>>> def function(number: int) -> IO[str]:

...     return IO(str(number))

>>> assert RequiresContextIOResult.from\_value(1).bind\_io(

...     function,

... )(RequiresContextIOResult.no\_args) == IOSuccess('1')

>>> assert RequiresContextIOResult.from\_failure(1).bind\_io(

...     function,

... )(RequiresContextIOResult.no\_args) == IOFailure(1)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`IO`](index.html#returns.io.IO "returns.io.IO")[`TypeVar`(`\_NewValueType`)]]) – 

Return type:

[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]

bind\_ioresult(*function*)[[source]](_modules/returns/context/requires_context_ioresult.html#RequiresContextIOResult.bind_ioresult)[¶](#returns.context.requires_context_ioresult.RequiresContextIOResult.bind_ioresult "Permalink to this definition")

Binds `IOResult` returning function to the current container.

```

>>> from returns.context import RequiresContextIOResult

>>> from returns.io import IOResult, IOSuccess, IOFailure

>>> def function(num: int) -> IOResult[int, str]:

...     return IOSuccess(num + 1) if num > 0 else IOFailure('<0')

>>> assert RequiresContextIOResult.from\_value(1).bind\_ioresult(

...     function,

... )(RequiresContextIOResult.no\_args) == IOSuccess(2)

>>> assert RequiresContextIOResult.from\_value(0).bind\_ioresult(

...     function,

... )(RequiresContextIOResult.no\_args) == IOFailure('<0')

>>> assert RequiresContextIOResult.from\_failure(':(').bind\_ioresult(

...     function,

... )(RequiresContextIOResult.no\_args) == IOFailure(':(')

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`IOResult`](index.html#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`)]]) – 

Return type:

[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]

alt(*function*)[[source]](_modules/returns/context/requires_context_ioresult.html#RequiresContextIOResult.alt)[¶](#returns.context.requires_context_ioresult.RequiresContextIOResult.alt "Permalink to this definition")

Composes failed container with a pure function.

```

>>> from returns.context import RequiresContextIOResult

>>> from returns.io import IOSuccess, IOFailure

>>> assert RequiresContextIOResult.from\_value(1).alt(

...     lambda x: x + 1,

... )(...) == IOSuccess(1)

>>> assert RequiresContextIOResult.from\_failure(1).alt(

...     lambda x: x + 1,

... )(...) == IOFailure(2)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ErrorType`)], `TypeVar`(`\_NewErrorType`)]) – 

Return type:

[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_NewErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]

lash(*function*)[[source]](_modules/returns/context/requires_context_ioresult.html#RequiresContextIOResult.lash)[¶](#returns.context.requires_context_ioresult.RequiresContextIOResult.lash "Permalink to this definition")

Composes this container with a function returning the same type.

```

>>> from returns.context import RequiresContextIOResult

>>> from returns.io import IOSuccess, IOFailure

>>> def lashable(

...     arg: str,

... ) -> RequiresContextIOResult[str, str, str]:

...      if len(arg) > 1:

...          return RequiresContextIOResult(

...              lambda deps: IOSuccess(deps + arg),

...          )

...      return RequiresContextIOResult(

...          lambda deps: IOFailure(arg + deps),

...      )

>>> assert RequiresContextIOResult.from\_value('a').lash(

...     lashable,

... )('c') == IOSuccess('a')

>>> assert RequiresContextIOResult.from\_failure('a').lash(

...     lashable,

... )('c') == IOFailure('ac')

>>> assert RequiresContextIOResult.from\_failure('aa').lash(

...     lashable,

... )('b') == IOSuccess('baa')

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ErrorType`)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult"), `TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_NewErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]]) – 

Return type:

[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_NewErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]

compose\_result(*function*)[[source]](_modules/returns/context/requires_context_ioresult.html#RequiresContextIOResult.compose_result)[¶](#returns.context.requires_context_ioresult.RequiresContextIOResult.compose_result "Permalink to this definition")

Composes inner `Result` with `ReaderIOResult` returning function.

Can be useful when you need an access to both states of the result.

```

>>> from returns.context import ReaderIOResult, NoDeps

>>> from returns.io import IOSuccess, IOFailure

>>> from returns.result import Result

>>> def count(

...    container: Result[int, int],

... ) -> ReaderIOResult[int, int, NoDeps]:

...     return ReaderIOResult.from\_result(

...         container.map(lambda x: x + 1).alt(abs),

...     )

>>> success = ReaderIOResult.from\_value(1)

>>> failure = ReaderIOResult.from\_failure(-1)

>>> assert success.compose\_result(count)(...) == IOSuccess(2)

>>> assert failure.compose\_result(count)(...) == IOFailure(1)

```

Parameters:

**function** (`Callable`[[[`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_ErrorType`)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult"), `TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]]) – 

Return type:

[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]

modify\_env(*function*)[[source]](_modules/returns/context/requires_context_ioresult.html#RequiresContextIOResult.modify_env)[¶](#returns.context.requires_context_ioresult.RequiresContextIOResult.modify_env "Permalink to this definition")

Allows to modify the environment type.

```

>>> from returns.context import RequiresContextIOResultE

>>> from returns.io import IOSuccess, impure\_safe

>>> def div(arg: int) -> RequiresContextIOResultE[float, int]:

...     return RequiresContextIOResultE(

...         impure\_safe(lambda deps: arg / deps),

...     )

>>> assert div(3).modify\_env(int)('2') == IOSuccess(1.5)

>>> assert div(3).modify\_env(int)('0').failure()

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_NewEnvType`)], `TypeVar`(`\_EnvType`, contravariant=True)]) – 

Return type:

[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_NewEnvType`)]

*classmethod* ask()[[source]](_modules/returns/context/requires_context_ioresult.html#RequiresContextIOResult.ask)[¶](#returns.context.requires_context_ioresult.RequiresContextIOResult.ask "Permalink to this definition")

Is used to get the current dependencies inside the call stack.

Similar to [`returns.context.requires\_context.RequiresContext.ask()`](#returns.context.requires_context.RequiresContext.ask "returns.context.requires_context.RequiresContext.ask"),

but returns `IOResult` instead of a regular value.

Please, refer to the docs there to learn how to use it.

One important note that is worth duplicating here:

you might need to provide `\_EnvType` explicitly,

so `mypy` will know about it statically.

```

>>> from returns.context import RequiresContextIOResultE

>>> from returns.io import IOSuccess

>>> assert RequiresContextIOResultE[int, int].ask().map(

...     str,

... )(1) == IOSuccess('1')

```

Return type:

[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_EnvType`, contravariant=True), `TypeVar`(`\_ErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]

*classmethod* from\_result(*inner\_value*)[[source]](_modules/returns/context/requires_context_ioresult.html#RequiresContextIOResult.from_result)[¶](#returns.context.requires_context_ioresult.RequiresContextIOResult.from_result "Permalink to this definition")

Creates new container with `Result` as a unit value.

```

>>> from returns.context import RequiresContextIOResult

>>> from returns.result import Success, Failure

>>> from returns.io import IOSuccess, IOFailure

>>> deps = RequiresContextIOResult.no\_args

>>> assert RequiresContextIOResult.from\_result(

...    Success(1),

... )(deps) == IOSuccess(1)

>>> assert RequiresContextIOResult.from\_result(

...    Failure(1),

... )(deps) == IOFailure(1)

```

Parameters:

**inner\_value** ([`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]) – 

Return type:

[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`), `Any`]

*classmethod* from\_io(*inner\_value*)[[source]](_modules/returns/context/requires_context_ioresult.html#RequiresContextIOResult.from_io)[¶](#returns.context.requires_context_ioresult.RequiresContextIOResult.from_io "Permalink to this definition")

Creates new container from successful `IO` value.

```

>>> from returns.io import IO, IOSuccess

>>> from returns.context import RequiresContextIOResult

>>> assert RequiresContextIOResult.from\_io(IO(1))(

...     RequiresContextIOResult.no\_args,

... ) == IOSuccess(1)

```

Parameters:

**inner\_value** ([`IO`](index.html#returns.io.IO "returns.io.IO")[`TypeVar`(`\_NewValueType`)]) – 

Return type:

[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_NewValueType`), `Any`, `Any`]

*classmethod* from\_failed\_io(*inner\_value*)[[source]](_modules/returns/context/requires_context_ioresult.html#RequiresContextIOResult.from_failed_io)[¶](#returns.context.requires_context_ioresult.RequiresContextIOResult.from_failed_io "Permalink to this definition")

Creates a new container from failed `IO` value.

```

>>> from returns.io import IO, IOFailure

>>> from returns.context import RequiresContextIOResult

>>> assert RequiresContextIOResult.from\_failed\_io(IO(1))(

...     RequiresContextIOResult.no\_args,

... ) == IOFailure(1)

```

Parameters:

**inner\_value** ([`IO`](index.html#returns.io.IO "returns.io.IO")[`TypeVar`(`\_NewErrorType`)]) – 

Return type:

[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`Any`, `TypeVar`(`\_NewErrorType`), `Any`]

*classmethod* from\_ioresult(*inner\_value*)[[source]](_modules/returns/context/requires_context_ioresult.html#RequiresContextIOResult.from_ioresult)[¶](#returns.context.requires_context_ioresult.RequiresContextIOResult.from_ioresult "Permalink to this definition")

Creates new container with `IOResult` as a unit value.

```

>>> from returns.context import RequiresContextIOResult

>>> from returns.io import IOSuccess, IOFailure

>>> deps = RequiresContextIOResult.no\_args

>>> assert RequiresContextIOResult.from\_ioresult(

...    IOSuccess(1),

... )(deps) == IOSuccess(1)

>>> assert RequiresContextIOResult.from\_ioresult(

...    IOFailure(1),

... )(deps) == IOFailure(1)

```

Parameters:

**inner\_value** ([`IOResult`](index.html#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]) – 

Return type:

[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`), `Any`]

*classmethod* from\_ioresult\_context(*inner\_value*)[[source]](_modules/returns/context/requires_context_ioresult.html#RequiresContextIOResult.from_ioresult_context)[¶](#returns.context.requires_context_ioresult.RequiresContextIOResult.from_ioresult_context "Permalink to this definition")

Creates new container with `ReaderIOResult` as a unit value.

```

>>> from returns.context import RequiresContextIOResult

>>> from returns.io import IOSuccess, IOFailure

>>> assert RequiresContextIOResult.from\_ioresult\_context(

...    RequiresContextIOResult.from\_value(1),

... )(...) == IOSuccess(1)

>>> assert RequiresContextIOResult.from\_ioresult\_context(

...    RequiresContextIOResult.from\_failure(1),

... )(...) == IOFailure(1)

```

Parameters:

**inner\_value** ([`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`), `TypeVar`(`\_NewEnvType`)]) – 

Return type:

[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`), `TypeVar`(`\_NewEnvType`)]

*classmethod* from\_typecast(*inner\_value*)[[source]](_modules/returns/context/requires_context_ioresult.html#RequiresContextIOResult.from_typecast)[¶](#returns.context.requires_context_ioresult.RequiresContextIOResult.from_typecast "Permalink to this definition")

You might end up with `RequiresContext[IOResult]` as a value.

This method is designed to turn it into `RequiresContextIOResult`.

It will save all the typing information.

It is just more useful!

```

>>> from returns.context import RequiresContext

>>> from returns.io import IOSuccess, IOFailure

>>> assert RequiresContextIOResult.from\_typecast(

...     RequiresContext.from\_value(IOSuccess(1)),

... )(RequiresContextIOResult.no\_args) == IOSuccess(1)

>>> assert RequiresContextIOResult.from\_typecast(

...     RequiresContext.from\_value(IOFailure(1)),

... )(RequiresContextIOResult.no\_args) == IOFailure(1)

```

Parameters:

**inner\_value** ([`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[[`IOResult`](index.html#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)], `TypeVar`(`\_EnvType`, contravariant=True)]) – 

Return type:

[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]

*classmethod* from\_context(*inner\_value*)[[source]](_modules/returns/context/requires_context_ioresult.html#RequiresContextIOResult.from_context)[¶](#returns.context.requires_context_ioresult.RequiresContextIOResult.from_context "Permalink to this definition")

Creates new container from `RequiresContext` as a success unit.

```

>>> from returns.context import RequiresContext

>>> from returns.io import IOSuccess

>>> assert RequiresContextIOResult.from\_context(

...     RequiresContext.from\_value(1),

... )(...) == IOSuccess(1)

```

Parameters:

**inner\_value** ([`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewEnvType`)]) – 

Return type:

[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_NewValueType`), `Any`, `TypeVar`(`\_NewEnvType`)]

*classmethod* from\_failed\_context(*inner\_value*)[[source]](_modules/returns/context/requires_context_ioresult.html#RequiresContextIOResult.from_failed_context)[¶](#returns.context.requires_context_ioresult.RequiresContextIOResult.from_failed_context "Permalink to this definition")

Creates new container from `RequiresContext` as a failure unit.

```

>>> from returns.context import RequiresContext

>>> from returns.io import IOFailure

>>> assert RequiresContextIOResult.from\_failed\_context(

...     RequiresContext.from\_value(1),

... )(...) == IOFailure(1)

```

Parameters:

**inner\_value** ([`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewEnvType`)]) – 

Return type:

[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`Any`, `TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewEnvType`)]

*classmethod* from\_result\_context(*inner\_value*)[[source]](_modules/returns/context/requires_context_ioresult.html#RequiresContextIOResult.from_result_context)[¶](#returns.context.requires_context_ioresult.RequiresContextIOResult.from_result_context "Permalink to this definition")

Creates new container from `RequiresContextResult` as a unit value.

```

>>> from returns.context import RequiresContextResult

>>> from returns.io import IOSuccess, IOFailure

>>> assert RequiresContextIOResult.from\_result\_context(

...     RequiresContextResult.from\_value(1),

... )(...) == IOSuccess(1)

>>> assert RequiresContextIOResult.from\_result\_context(

...     RequiresContextResult.from\_failure(1),

... )(...) == IOFailure(1)

```

Parameters:

**inner\_value** ([`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`), `TypeVar`(`\_NewEnvType`)]) – 

Return type:

[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`), `TypeVar`(`\_NewEnvType`)]

*classmethod* from\_value(*inner\_value*)[[source]](_modules/returns/context/requires_context_ioresult.html#RequiresContextIOResult.from_value)[¶](#returns.context.requires_context_ioresult.RequiresContextIOResult.from_value "Permalink to this definition")

Creates new container with `IOSuccess(inner\_value)` as a unit value.

```

>>> from returns.context import RequiresContextIOResult

>>> from returns.io import IOSuccess

>>> assert RequiresContextIOResult.from\_value(1)(

...    RequiresContextIOResult.no\_args,

... ) == IOSuccess(1)

```

Parameters:

**inner\_value** (`TypeVar`(`\_NewValueType`)) – 

Return type:

[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_NewValueType`), `Any`, `Any`]

*classmethod* from\_failure(*inner\_value*)[[source]](_modules/returns/context/requires_context_ioresult.html#RequiresContextIOResult.from_failure)[¶](#returns.context.requires_context_ioresult.RequiresContextIOResult.from_failure "Permalink to this definition")

Creates new container with `IOFailure(inner\_value)` as a unit value.

```

>>> from returns.context import RequiresContextIOResult

>>> from returns.io import IOFailure

>>> assert RequiresContextIOResult.from\_failure(1)(

...     RequiresContextIOResult.no\_args,

... ) == IOFailure(1)

```

Parameters:

**inner\_value** (`TypeVar`(`\_NewErrorType`)) – 

Return type:

[`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`Any`, `TypeVar`(`\_NewErrorType`), `Any`]

RequiresContextIOResultE[¶](#returns.context.requires_context_ioresult.RequiresContextIOResultE "Permalink to this definition")

Alias for a popular case when `Result` has `Exception` as error type.

alias of [`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`\_ValueType`, `Exception`, `\_EnvType`]

ReaderIOResult[¶](#returns.context.requires_context_ioresult.ReaderIOResult "Permalink to this definition")

Alias to save you some typing. Uses original name from Haskell.

Parameters:

**inner\_value** (`Callable`[[`TypeVar`(`\_EnvType`, contravariant=True)], [`IOResult`](index.html#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_ErrorType`)]]) – 

ReaderIOResultE[¶](#returns.context.requires_context_ioresult.ReaderIOResultE "Permalink to this definition")

Alias to save you some typing. Uses `Exception` as error type.

alias of [`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`\_ValueType`, `Exception`, `\_EnvType`]

#### RequiresContextFutureResult[¶](#requirescontextfutureresult "Permalink to this heading")

 classDiagram

 BaseContainer <|-- RequiresContextFutureResult

 FutureResultLikeN <|-- RequiresContextFutureResult

 ReaderFutureResultBasedN <|-- RequiresContextFutureResult

 SupportsKindN <|-- RequiresContextFutureResult

 

*final class* RequiresContextFutureResult(*inner\_value*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult "Permalink to this definition")

Bases: [`BaseContainer`](index.html#returns.primitives.container.BaseContainer "returns.primitives.container.BaseContainer"), [`SupportsKindN`](index.html#returns.primitives.hkt.SupportsKindN "returns.primitives.hkt.SupportsKindN")[[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult"), `\_ValueType`, `\_ErrorType`, `\_EnvType`], [`ReaderFutureResultBasedN`](index.html#returns.interfaces.specific.reader_future_result.ReaderFutureResultBasedN "returns.interfaces.specific.reader_future_result.ReaderFutureResultBasedN")[`\_ValueType`, `\_ErrorType`, `\_EnvType`], [`FutureResultLikeN`](index.html#returns.interfaces.specific.future_result.FutureResultLikeN "returns.interfaces.specific.future_result.FutureResultLikeN")[`\_ValueType`, `\_ErrorType`, `\_EnvType`]

The `RequiresContextFutureResult` combinator.

This probably the main type people are going to use in `async` programs.

See [`returns.context.requires\_context.RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext"),

[`returns.context.requires\_context\_result.RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult"),

and

`returns.context.requires\_context\_result.RequiresContextIOResult`

for more docs.

This is just a handy wrapper around

`RequiresContext[FutureResult[a, b], env]`

which represents a context-dependent impure async operation that might fail.

So, this is a thin wrapper, without any changes in logic.

Why do we need this wrapper? That’s just for better usability!

This way `RequiresContextIOResult` allows to simply work with:

* raw values and pure functions

* `RequiresContext` values and pure functions returning it

* `RequiresContextResult` values and pure functions returning it

* `RequiresContextIOResult` values and pure functions returning it

* `Result` and pure functions returning it

* `IOResult` and functions returning it

* `FutureResult` and functions returning it

* other `RequiresContextFutureResult` related functions and values

This is a complex type for complex tasks!

Important implementation details

Due it is meaning, `RequiresContextFutureResult`

cannot have `Success` and `Failure` subclasses.

We only have just one type. That’s by design.

Different converters are also not supported for this type.

Use converters inside the `RequiresContext` context, not outside.

See also

* <https://dev.to/gcanti/getting-started-with-fp-ts-reader-1ie5>

* <https://en.wikipedia.org/wiki/Lazy_evaluation>

* <https://bit.ly/2R8l4WK>

* <https://bit.ly/2RwP4fp>

Parameters:

**inner\_value** (`Callable`[[`TypeVar`(`\_EnvType`, contravariant=True)], [`FutureResult`](index.html#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_ErrorType`, covariant=True)]]) – 

no\_args*: ClassVar[NoDeps]* *= <object object>*[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.no_args "Permalink to this definition")

A convenient placeholder to call methods created by .from\_value().

swap()[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.swap)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.swap "Permalink to this definition")

Swaps value and error types.

So, values become errors and errors become values.

It is useful when you have to work with errors a lot.

And since we have a lot of `.bind\_` related methods

and only a single `.lash` - it is easier to work with values.

```

>>> import anyio

>>> from returns.context import RequiresContextFutureResult

>>> from returns.io import IOSuccess, IOFailure

>>> success = RequiresContextFutureResult.from\_value(1)

>>> failure = RequiresContextFutureResult.from\_failure(1)

>>> assert anyio.run(success.swap(), ...) == IOFailure(1)

>>> assert anyio.run(failure.swap(), ...) == IOSuccess(1)

```

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

map(*function*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.map)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.map "Permalink to this definition")

Composes successful container with a pure function.

```

>>> import anyio

>>> from returns.context import RequiresContextFutureResult

>>> from returns.io import IOSuccess, IOFailure

>>> assert anyio.run(RequiresContextFutureResult.from\_value(1).map(

...     lambda x: x + 1,

... )(...).awaitable) == IOSuccess(2)

>>> assert anyio.run(RequiresContextFutureResult.from\_failure(1).map(

...     lambda x: x + 1,

... )(...).awaitable) == IOFailure(1)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `TypeVar`(`\_NewValueType`)]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

apply(*container*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.apply)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.apply "Permalink to this definition")

Calls a wrapped function in a container on this container.

```

>>> import anyio

>>> from returns.context import RequiresContextFutureResult

>>> from returns.io import IOSuccess, IOFailure

>>> def transform(arg: str) -> str:

...     return arg + 'b'

>>> assert anyio.run(

...    RequiresContextFutureResult.from\_value('a').apply(

...        RequiresContextFutureResult.from\_value(transform),

...    ),

...    RequiresContextFutureResult.no\_args,

... ) == IOSuccess('ab')

>>> assert anyio.run(

...    RequiresContextFutureResult.from\_failure('a').apply(

...        RequiresContextFutureResult.from\_value(transform),

...    ),

...    RequiresContextFutureResult.no\_args,

... ) == IOFailure('a')

```

Parameters:

**container** ([`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult"), `Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `TypeVar`(`\_NewValueType`)], `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

bind(*function*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.bind)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind "Permalink to this definition")

Composes this container with a function returning the same type.

```

>>> import anyio

>>> from returns.context import RequiresContextFutureResult

>>> from returns.future import FutureResult

>>> from returns.io import IOSuccess, IOFailure

>>> def function(

...     number: int,

... ) -> RequiresContextFutureResult[str, int, int]:

...     # `deps` has `int` type here:

...     return RequiresContextFutureResult(

...         lambda deps: FutureResult.from\_value(str(number + deps)),

...     )

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_value(2).bind(function),

...     3,

... ) == IOSuccess('5')

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_failure(2).bind(function),

...     3,

... ) == IOFailure(2)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult"), `TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

bind\_context\_future\_result(*function*)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind_context_future_result "Permalink to this definition")

Alias for bind\_context\_future\_result method,

it is the same as bind here.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult"), `TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

bind\_async(*function*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.bind_async)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind_async "Permalink to this definition")

Composes this container with a async function returning the same type.

```

>>> import anyio

>>> from returns.context import RequiresContextFutureResult

>>> from returns.io import IOSuccess, IOFailure

>>> async def function(

...     number: int,

... ) -> RequiresContextFutureResult[str, int, int]:

...     return RequiresContextFutureResult.from\_value(number + 1)

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_value(1).bind\_async(

...        function,

...     ),

...     RequiresContextFutureResult.no\_args,

... ) == IOSuccess(2)

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_failure(1).bind\_async(

...        function,

...     ),

...     RequiresContextFutureResult.no\_args,

... ) == IOFailure(1)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `Awaitable`[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult"), `TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]]]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

bind\_async\_context\_future\_result(*function*)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind_async_context_future_result "Permalink to this definition")

Alias for bind\_async\_context\_future\_result method,

it is the same as bind\_async here.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `Awaitable`[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult"), `TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]]]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

bind\_awaitable(*function*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.bind_awaitable)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind_awaitable "Permalink to this definition")

Allows to compose a container and a regular `async` function.

This function should return plain, non-container value.

See [`bind\_async()`](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind_async "returns.context.requires_context_future_result.RequiresContextFutureResult.bind_async")

to bind `async` function that returns a container.

```

>>> import anyio

>>> from returns.context import RequiresContextFutureResult

>>> from returns.io import IOSuccess, IOFailure

>>> async def coroutine(x: int) -> int:

...    return x + 1

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_value(1).bind\_awaitable(

...         coroutine,

...     ),

...     RequiresContextFutureResult.no\_args,

... ) == IOSuccess(2)

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_failure(1).bind\_awaitable(

...         coroutine,

...     ),

...     RequiresContextFutureResult.no\_args,

... ) == IOFailure(1)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `Awaitable`[`TypeVar`(`\_NewValueType`)]]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

bind\_result(*function*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.bind_result)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind_result "Permalink to this definition")

Binds `Result` returning function to the current container.

```

>>> import anyio

>>> from returns.context import RequiresContextFutureResult

>>> from returns.result import Success, Result

>>> from returns.io import IOSuccess, IOFailure

>>> def function(num: int) -> Result[int, str]:

...     return Success(num + 1)

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_value(1).bind\_result(

...         function,

...     ),

...     RequiresContextFutureResult.no\_args,

... ) == IOSuccess(2)

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_failure(':(').bind\_result(

...         function,

...     ),

...     RequiresContextFutureResult.no\_args,

... ) == IOFailure(':(')

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

bind\_context(*function*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.bind_context)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind_context "Permalink to this definition")

Binds `RequiresContext` returning function to current container.

```

>>> import anyio

>>> from returns.context import RequiresContext

>>> from returns.io import IOSuccess, IOFailure

>>> def function(arg: int) -> RequiresContext[int, str]:

...     return RequiresContext(lambda deps: len(deps) + arg)

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_value(2).bind\_context(

...         function,

...     ),

...     'abc',

... ) == IOSuccess(5)

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_failure(0).bind\_context(

...         function,

...     ),

...     'abc',

... ) == IOFailure(0)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_EnvType`, contravariant=True)]]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

bind\_context\_result(*function*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.bind_context_result)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind_context_result "Permalink to this definition")

Binds `RequiresContextResult` returning function to the current one.

```

>>> import anyio

>>> from returns.context import RequiresContextResult

>>> from returns.io import IOSuccess, IOFailure

>>> from returns.result import Success

>>> def function(arg: int) -> RequiresContextResult[int, int, str]:

...     return RequiresContextResult(

...         lambda deps: Success(len(deps) + arg),

...     )

>>> instance = RequiresContextFutureResult.from\_value(

...    2,

... ).bind\_context\_result(

...     function,

... )('abc')

>>> assert anyio.run(instance.awaitable) == IOSuccess(5)

>>> instance = RequiresContextFutureResult.from\_failure(

...    2,

... ).bind\_context\_result(

...     function,

... )('abc')

>>> assert anyio.run(instance.awaitable) == IOFailure(2)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

bind\_context\_ioresult(*function*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.bind_context_ioresult)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind_context_ioresult "Permalink to this definition")

Binds `RequiresContextIOResult` returning function to the current one.

```

>>> import anyio

>>> from returns.context import RequiresContextIOResult

>>> from returns.io import IOSuccess, IOFailure

>>> def function(arg: int) -> RequiresContextIOResult[int, int, str]:

...     return RequiresContextIOResult(

...         lambda deps: IOSuccess(len(deps) + arg),

...     )

>>> instance = RequiresContextFutureResult.from\_value(

...    2,

... ).bind\_context\_ioresult(

...     function,

... )('abc')

>>> assert anyio.run(instance.awaitable) == IOSuccess(5)

>>> instance = RequiresContextFutureResult.from\_failure(

...    2,

... ).bind\_context\_ioresult(

...     function,

... )('abc')

>>> assert anyio.run(instance.awaitable) == IOFailure(2)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

bind\_io(*function*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.bind_io)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind_io "Permalink to this definition")

Binds `IO` returning function to the current container.

```

>>> import anyio

>>> from returns.context import RequiresContextFutureResult

>>> from returns.io import IO, IOSuccess, IOFailure

>>> def do\_io(number: int) -> IO[str]:

...     return IO(str(number))  # not IO operation actually

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_value(1).bind\_io(do\_io),

...     RequiresContextFutureResult.no\_args,

... ) == IOSuccess('1')

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_failure(1).bind\_io(do\_io),

...     RequiresContextFutureResult.no\_args,

... ) == IOFailure(1)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`IO`](index.html#returns.io.IO "returns.io.IO")[`TypeVar`(`\_NewValueType`)]]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

bind\_ioresult(*function*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.bind_ioresult)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind_ioresult "Permalink to this definition")

Binds `IOResult` returning function to the current container.

```

>>> import anyio

>>> from returns.context import RequiresContextFutureResult

>>> from returns.io import IOResult, IOSuccess, IOFailure

>>> def function(num: int) -> IOResult[int, str]:

...     return IOSuccess(num + 1)

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_value(1).bind\_ioresult(

...         function,

...     ),

...     RequiresContextFutureResult.no\_args,

... ) == IOSuccess(2)

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_failure(':(').bind\_ioresult(

...         function,

...     ),

...     RequiresContextFutureResult.no\_args,

... ) == IOFailure(':(')

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`IOResult`](index.html#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

bind\_future(*function*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.bind_future)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind_future "Permalink to this definition")

Binds `Future` returning function to the current container.

```

>>> import anyio

>>> from returns.context import RequiresContextFutureResult

>>> from returns.future import Future

>>> from returns.io import IOSuccess, IOFailure

>>> def function(num: int) -> Future[int]:

...     return Future.from\_value(num + 1)

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_value(1).bind\_future(

...         function,

...     ),

...     RequiresContextFutureResult.no\_args,

... ) == IOSuccess(2)

>>> failed = RequiresContextFutureResult.from\_failure(':(')

>>> assert anyio.run(

...     failed.bind\_future(function),

...     RequiresContextFutureResult.no\_args,

... ) == IOFailure(':(')

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`Future`](index.html#returns.future.Future "returns.future.Future")[`TypeVar`(`\_NewValueType`)]]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

bind\_future\_result(*function*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.bind_future_result)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind_future_result "Permalink to this definition")

Binds `FutureResult` returning function to the current container.

```

>>> import anyio

>>> from returns.context import RequiresContextFutureResult

>>> from returns.future import FutureResult

>>> from returns.io import IOSuccess, IOFailure

>>> def function(num: int) -> FutureResult[int, str]:

...     return FutureResult.from\_value(num + 1)

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_value(1).bind\_future\_result(

...         function,

...     ),

...     RequiresContextFutureResult.no\_args,

... ) == IOSuccess(2)

>>> failed = RequiresContextFutureResult.from\_failure(':(')

>>> assert anyio.run(

...     failed.bind\_future\_result(function),

...     RequiresContextFutureResult.no\_args,

... ) == IOFailure(':(')

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], [`FutureResult`](index.html#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

bind\_async\_future(*function*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.bind_async_future)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind_async_future "Permalink to this definition")

Binds `Future` returning async function to the current container.

```

>>> import anyio

>>> from returns.context import RequiresContextFutureResult

>>> from returns.future import Future

>>> from returns.io import IOSuccess, IOFailure

>>> async def function(num: int) -> Future[int]:

...     return Future.from\_value(num + 1)

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_value(1).bind\_async\_future(

...         function,

...     ),

...     RequiresContextFutureResult.no\_args,

... ) == IOSuccess(2)

>>> failed = RequiresContextFutureResult.from\_failure(':(')

>>> assert anyio.run(

...     failed.bind\_async\_future(function),

...     RequiresContextFutureResult.no\_args,

... ) == IOFailure(':(')

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `Awaitable`[[`Future`](index.html#returns.future.Future "returns.future.Future")[`TypeVar`(`\_NewValueType`)]]]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

bind\_async\_future\_result(*function*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.bind_async_future_result)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.bind_async_future_result "Permalink to this definition")

Bind `FutureResult` returning async function to the current container.

```

>>> import anyio

>>> from returns.context import RequiresContextFutureResult

>>> from returns.future import FutureResult

>>> from returns.io import IOSuccess, IOFailure

>>> async def function(num: int) -> FutureResult[int, str]:

...     return FutureResult.from\_value(num + 1)

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_value(

...         1,

...     ).bind\_async\_future\_result(

...         function,

...     ),

...     RequiresContextFutureResult.no\_args,

... ) == IOSuccess(2)

>>> failed = RequiresContextFutureResult.from\_failure(':(')

>>> assert anyio.run(

...     failed.bind\_async\_future\_result(function),

...     RequiresContextFutureResult.no\_args,

... ) == IOFailure(':(')

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ValueType`, covariant=True)], `Awaitable`[[`FutureResult`](index.html#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True)]]]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

alt(*function*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.alt)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.alt "Permalink to this definition")

Composes failed container with a pure function.

```

>>> import anyio

>>> from returns.context import RequiresContextFutureResult

>>> from returns.io import IOSuccess, IOFailure

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_value(1).alt(

...        lambda x: x + 1,

...     ),

...     RequiresContextFutureResult.no\_args,

... ) == IOSuccess(1)

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_failure(1).alt(

...        lambda x: x + 1,

...     ),

...     RequiresContextFutureResult.no\_args,

... ) == IOFailure(2)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ErrorType`, covariant=True)], `TypeVar`(`\_NewErrorType`)]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_NewErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]

lash(*function*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.lash)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.lash "Permalink to this definition")

Composes this container with a function returning the same type.

```

>>> import anyio

>>> from returns.context import RequiresContextFutureResult

>>> from returns.future import FutureResult

>>> from returns.io import IOSuccess

>>> def lashable(

...     arg: str,

... ) -> RequiresContextFutureResult[str, str, str]:

...      return RequiresContextFutureResult(

...          lambda deps: FutureResult.from\_value(

...              deps + arg,

...          ),

...      )

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_value('a').lash(lashable),

...     'c',

... ) == IOSuccess('a')

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_failure('aa').lash(

...         lashable,

...     ),

...     'b',

... ) == IOSuccess('baa')

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_ErrorType`, covariant=True)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult"), `TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_NewErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_NewErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]

compose\_result(*function*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.compose_result)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.compose_result "Permalink to this definition")

Composes inner `Result` with `ReaderFutureResult` returning func.

Can be useful when you need an access to both states of the result.

```

>>> import anyio

>>> from returns.context import ReaderFutureResult, NoDeps

>>> from returns.io import IOSuccess, IOFailure

>>> from returns.result import Result

>>> def count(

...    container: Result[int, int],

... ) -> ReaderFutureResult[int, int, NoDeps]:

...     return ReaderFutureResult.from\_result(

...         container.map(lambda x: x + 1).alt(abs),

...     )

>>> success = ReaderFutureResult.from\_value(1)

>>> failure = ReaderFutureResult.from\_failure(-1)

>>> assert anyio.run(

...     success.compose\_result(count), ReaderFutureResult.no\_args,

... ) == IOSuccess(2)

>>> assert anyio.run(

...     failure.compose\_result(count), ReaderFutureResult.no\_args,

... ) == IOFailure(1)

```

Parameters:

**function** (`Callable`[[[`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_ErrorType`, covariant=True)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult"), `TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

modify\_env(*function*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.modify_env)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.modify_env "Permalink to this definition")

Allows to modify the environment type.

```

>>> import anyio

>>> from returns.future import future\_safe, asyncify

>>> from returns.context import RequiresContextFutureResultE

>>> from returns.io import IOSuccess

>>> def div(arg: int) -> RequiresContextFutureResultE[float, int]:

...     return RequiresContextFutureResultE(

...         future\_safe(asyncify(lambda deps: arg / deps)),

...     )

>>> assert anyio.run(div(3).modify\_env(int), '2') == IOSuccess(1.5)

>>> assert anyio.run(div(3).modify\_env(int), '0').failure()

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_NewEnvType`)], `TypeVar`(`\_EnvType`, contravariant=True)]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_NewEnvType`)]

*classmethod* ask()[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.ask)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.ask "Permalink to this definition")

Is used to get the current dependencies inside the call stack.

Similar to

[`returns.context.requires\_context.RequiresContext.ask()`](#returns.context.requires_context.RequiresContext.ask "returns.context.requires_context.RequiresContext.ask"),

but returns `FutureResult` instead of a regular value.

Please, refer to the docs there to learn how to use it.

One important note that is worth duplicating here:

you might need to provide type annotations explicitly,

so `mypy` will know about it statically.

```

>>> import anyio

>>> from returns.context import RequiresContextFutureResultE

>>> from returns.io import IOSuccess

>>> assert anyio.run(

...     RequiresContextFutureResultE[int, int].ask().map(str),

...     1,

... ) == IOSuccess('1')

```

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_EnvType`, contravariant=True), `TypeVar`(`\_ErrorType`, covariant=True), `TypeVar`(`\_EnvType`, contravariant=True)]

*classmethod* from\_result(*inner\_value*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.from_result)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.from_result "Permalink to this definition")

Creates new container with `Result` as a unit value.

```

>>> import anyio

>>> from returns.context import RequiresContextFutureResult

>>> from returns.result import Success, Failure

>>> from returns.io import IOSuccess, IOFailure

>>> assert anyio.run(

...    RequiresContextFutureResult.from\_result(Success(1)),

...    RequiresContextFutureResult.no\_args,

... ) == IOSuccess(1)

>>> assert anyio.run(

...    RequiresContextFutureResult.from\_result(Failure(1)),

...    RequiresContextFutureResult.no\_args,

... ) == IOFailure(1)

```

Parameters:

**inner\_value** ([`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`), `Any`]

*classmethod* from\_io(*inner\_value*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.from_io)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.from_io "Permalink to this definition")

Creates new container from successful `IO` value.

```

>>> import anyio

>>> from returns.io import IO, IOSuccess

>>> from returns.context import RequiresContextFutureResult

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_io(IO(1)),

...     RequiresContextFutureResult.no\_args,

... ) == IOSuccess(1)

```

Parameters:

**inner\_value** ([`IO`](index.html#returns.io.IO "returns.io.IO")[`TypeVar`(`\_NewValueType`)]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `Any`, `Any`]

*classmethod* from\_failed\_io(*inner\_value*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.from_failed_io)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.from_failed_io "Permalink to this definition")

Creates a new container from failed `IO` value.

```

>>> import anyio

>>> from returns.io import IO, IOFailure

>>> from returns.context import RequiresContextFutureResult

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_failed\_io(IO(1)),

...     RequiresContextFutureResult.no\_args,

... ) == IOFailure(1)

```

Parameters:

**inner\_value** ([`IO`](index.html#returns.io.IO "returns.io.IO")[`TypeVar`(`\_NewErrorType`)]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`Any`, `TypeVar`(`\_NewErrorType`), `Any`]

*classmethod* from\_ioresult(*inner\_value*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.from_ioresult)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.from_ioresult "Permalink to this definition")

Creates new container with `IOResult` as a unit value.

```

>>> import anyio

>>> from returns.context import RequiresContextFutureResult

>>> from returns.io import IOSuccess, IOFailure

>>> assert anyio.run(

...    RequiresContextFutureResult.from\_ioresult(IOSuccess(1)),

...    RequiresContextFutureResult.no\_args,

... ) == IOSuccess(1)

>>> assert anyio.run(

...    RequiresContextFutureResult.from\_ioresult(IOFailure(1)),

...    RequiresContextFutureResult.no\_args,

... ) == IOFailure(1)

```

Parameters:

**inner\_value** ([`IOResult`](index.html#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`), `Any`]

*classmethod* from\_future(*inner\_value*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.from_future)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.from_future "Permalink to this definition")

Creates new container with successful `Future` as a unit value.

```

>>> import anyio

>>> from returns.context import RequiresContextFutureResult

>>> from returns.future import Future

>>> from returns.io import IOSuccess

>>> assert anyio.run(

...    RequiresContextFutureResult.from\_future(Future.from\_value(1)),

...    RequiresContextFutureResult.no\_args,

... ) == IOSuccess(1)

```

Parameters:

**inner\_value** ([`Future`](index.html#returns.future.Future "returns.future.Future")[`TypeVar`(`\_NewValueType`)]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `Any`, `Any`]

*classmethod* from\_failed\_future(*inner\_value*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.from_failed_future)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.from_failed_future "Permalink to this definition")

Creates new container with failed `Future` as a unit value.

```

>>> import anyio

>>> from returns.context import RequiresContextFutureResult

>>> from returns.future import Future

>>> from returns.io import IOFailure

>>> assert anyio.run(

...    RequiresContextFutureResult.from\_failed\_future(

...        Future.from\_value(1),

...    ),

...    RequiresContextFutureResult.no\_args,

... ) == IOFailure(1)

```

Parameters:

**inner\_value** ([`Future`](index.html#returns.future.Future "returns.future.Future")[`TypeVar`(`\_NewErrorType`)]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`Any`, `TypeVar`(`\_NewErrorType`), `Any`]

*classmethod* from\_future\_result\_context(*inner\_value*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.from_future_result_context)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.from_future_result_context "Permalink to this definition")

Creates new container with `ReaderFutureResult` as a unit value.

```

>>> import anyio

>>> from returns.context import RequiresContextFutureResult

>>> from returns.io import IOSuccess, IOFailure

>>> assert anyio.run(

...    RequiresContextFutureResult.from\_future\_result\_context(

...        RequiresContextFutureResult.from\_value(1),

...    ),

...    RequiresContextFutureResult.no\_args,

... ) == IOSuccess(1)

>>> assert anyio.run(

...    RequiresContextFutureResult.from\_future\_result\_context(

...        RequiresContextFutureResult.from\_failure(1),

...    ),

...    RequiresContextFutureResult.no\_args,

... ) == IOFailure(1)

```

Parameters:

**inner\_value** ([`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`), `TypeVar`(`\_NewEnvType`)]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`), `TypeVar`(`\_NewEnvType`)]

*classmethod* from\_future\_result(*inner\_value*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.from_future_result)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.from_future_result "Permalink to this definition")

Creates new container with `FutureResult` as a unit value.

```

>>> import anyio

>>> from returns.context import RequiresContextFutureResult

>>> from returns.future import FutureResult

>>> from returns.io import IOSuccess, IOFailure

>>> assert anyio.run(

...    RequiresContextFutureResult.from\_future\_result(

...        FutureResult.from\_value(1),

...    ),

...    RequiresContextFutureResult.no\_args,

... ) == IOSuccess(1)

>>> assert anyio.run(

...    RequiresContextFutureResult.from\_future\_result(

...        FutureResult.from\_failure(1),

...    ),

...    RequiresContextFutureResult.no\_args,

... ) == IOFailure(1)

```

Parameters:

**inner\_value** ([`FutureResult`](index.html#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`), `Any`]

*classmethod* from\_typecast(*inner\_value*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.from_typecast)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.from_typecast "Permalink to this definition")

You might end up with `RequiresContext[FutureResult]` as a value.

This method is designed to turn it into `RequiresContextFutureResult`.

It will save all the typing information.

It is just more useful!

```

>>> import anyio

>>> from returns.context import RequiresContext

>>> from returns.future import FutureResult

>>> from returns.io import IOSuccess, IOFailure

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_typecast(

...         RequiresContext.from\_value(FutureResult.from\_value(1)),

...     ),

...     RequiresContextFutureResult.no\_args,

... ) == IOSuccess(1)

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_typecast(

...         RequiresContext.from\_value(FutureResult.from\_failure(1)),

...     ),

...     RequiresContextFutureResult.no\_args,

... ) == IOFailure(1)

```

Parameters:

**inner\_value** ([`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[[`FutureResult`](index.html#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`)], `TypeVar`(`\_EnvType`, contravariant=True)]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`), `TypeVar`(`\_EnvType`, contravariant=True)]

*classmethod* from\_context(*inner\_value*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.from_context)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.from_context "Permalink to this definition")

Creates new container from `RequiresContext` as a success unit.

```

>>> import anyio

>>> from returns.context import RequiresContext

>>> from returns.io import IOSuccess

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_context(

...         RequiresContext.from\_value(1),

...     ),

...     RequiresContextFutureResult.no\_args,

... ) == IOSuccess(1)

```

Parameters:

**inner\_value** ([`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewEnvType`)]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `Any`, `TypeVar`(`\_NewEnvType`)]

*classmethod* from\_failed\_context(*inner\_value*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.from_failed_context)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.from_failed_context "Permalink to this definition")

Creates new container from `RequiresContext` as a failure unit.

```

>>> import anyio

>>> from returns.context import RequiresContext

>>> from returns.io import IOFailure

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_failed\_context(

...         RequiresContext.from\_value(1),

...     ),

...     RequiresContextFutureResult.no\_args,

... ) == IOFailure(1)

```

Parameters:

**inner\_value** ([`RequiresContext`](#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewEnvType`)]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`Any`, `TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewEnvType`)]

*classmethod* from\_result\_context(*inner\_value*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.from_result_context)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.from_result_context "Permalink to this definition")

Creates new container from `RequiresContextResult` as a unit value.

```

>>> import anyio

>>> from returns.context import RequiresContextResult

>>> from returns.io import IOSuccess, IOFailure

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_result\_context(

...         RequiresContextResult.from\_value(1),

...     ),

...     RequiresContextFutureResult.no\_args,

... ) == IOSuccess(1)

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_result\_context(

...         RequiresContextResult.from\_failure(1),

...     ),

...     RequiresContextFutureResult.no\_args,

... ) == IOFailure(1)

```

Parameters:

**inner\_value** ([`RequiresContextResult`](#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`), `TypeVar`(`\_NewEnvType`)]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`), `TypeVar`(`\_NewEnvType`)]

*classmethod* from\_ioresult\_context(*inner\_value*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.from_ioresult_context)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.from_ioresult_context "Permalink to this definition")

Creates new container from `RequiresContextIOResult` as a unit value.

```

>>> import anyio

>>> from returns.context import RequiresContextIOResult

>>> from returns.io import IOSuccess, IOFailure

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_ioresult\_context(

...         RequiresContextIOResult.from\_value(1),

...     ),

...     RequiresContextFutureResult.no\_args,

... ) == IOSuccess(1)

>>> assert anyio.run(

...     RequiresContextFutureResult.from\_ioresult\_context(

...         RequiresContextIOResult.from\_failure(1),

...     ),

...     RequiresContextFutureResult.no\_args,

... ) == IOFailure(1)

```

Parameters:

**inner\_value** ([`RequiresContextIOResult`](#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`), `TypeVar`(`\_NewEnvType`)]) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_NewValueType`), `TypeVar`(`\_NewErrorType`), `TypeVar`(`\_NewEnvType`)]

*classmethod* from\_value(*inner\_value*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.from_value)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.from_value "Permalink to this definition")

Creates new container with successful `FutureResult` as a unit value.

```

>>> import anyio

>>> from returns.context import RequiresContextFutureResult

>>> from returns.io import IOSuccess

>>> assert anyio.run(RequiresContextFutureResult.from\_value(1)(

...    RequiresContextFutureResult.no\_args,

... ).awaitable) == IOSuccess(1)

```

Parameters:

**inner\_value** (`TypeVar`(`\_FirstType`)) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`TypeVar`(`\_FirstType`), `Any`, `Any`]

*classmethod* from\_failure(*inner\_value*)[[source]](_modules/returns/context/requires_context_future_result.html#RequiresContextFutureResult.from_failure)[¶](#returns.context.requires_context_future_result.RequiresContextFutureResult.from_failure "Permalink to this definition")

Creates new container with failed `FutureResult` as a unit value.

```

>>> import anyio

>>> from returns.context import RequiresContextFutureResult

>>> from returns.io import IOFailure

>>> assert anyio.run(RequiresContextFutureResult.from\_failure(1)(

...     RequiresContextFutureResult.no\_args,

... ).awaitable) == IOFailure(1)

```

Parameters:

**inner\_value** (`TypeVar`(`\_FirstType`)) – 

Return type:

[`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`Any`, `TypeVar`(`\_FirstType`), `Any`]

RequiresContextFutureResultE[¶](#returns.context.requires_context_future_result.RequiresContextFutureResultE "Permalink to this definition")

Alias for a popular case when `Result` has `Exception` as error type.

alias of [`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`\_ValueType`, `Exception`, `\_EnvType`]

ReaderFutureResult[¶](#returns.context.requires_context_future_result.ReaderFutureResult "Permalink to this definition")

Sometimes RequiresContextFutureResult is too long to type.

Parameters:

**inner\_value** (`Callable`[[`TypeVar`(`\_EnvType`, contravariant=True)], [`FutureResult`](index.html#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_ValueType`, covariant=True), `TypeVar`(`\_ErrorType`, covariant=True)]]) – 

ReaderFutureResultE[¶](#returns.context.requires_context_future_result.ReaderFutureResultE "Permalink to this definition")

Alias to save you some typing. Uses `Exception` as error type.

alias of [`RequiresContextFutureResult`](#returns.context.requires_context_future_result.RequiresContextFutureResult "returns.context.requires_context_future_result.RequiresContextFutureResult")[`\_ValueType`, `Exception`, `\_EnvType`]

Create your own container[¶](#create-your-own-container "Permalink to this heading")

------------------------------------------------------------------------------------

This tutorial will guide you through the process of creating

your own containers.

### Step 0: Motivation[¶](#step-0-motivation "Permalink to this heading")

First things first, why would anyone want to create a custom containers?

The great idea about “containers” in functional programming

is that it can be literally anything. There are endless use-cases.

You can create your own primitives for working

with some language-or-framework specific problem,

or just model your business domain.

You can copy ideas from other languages or just compose existing containers

for better usability

(like `IOResult` is the composition of `IO` and `Result`).

Example

We are going to implement a `Pair` container for this example.

What is a `Pair`? Well, it is literally a pair of two values.

No more, no less. Similar to a `Tuple[FirstType, SecondType]`.

But with extra goodies.

Note

You can find all [code samples here](https://github.com/dry-python/returns/tree/master/tests/test_examples).

### Step 1: Choosing right interfaces[¶](#step-1-choosing-right-interfaces "Permalink to this heading")

After you came up with the idea, you will need to make a decision:

what capabilities my container must have?

Basically, you should decide what [Interfaces](index.html#interfaces) you will subtype and what

methods and laws will be present in your type.

You can create just a [`returns.interfaces.mappable.MappableN`](index.html#returns.interfaces.mappable.MappableN "returns.interfaces.mappable.MappableN")

or choose a full featured [`returns.interfaces.container.ContainerN`](index.html#returns.interfaces.container.ContainerN "returns.interfaces.container.ContainerN").

You can also choose some specific interfaces to use,

like [`returns.interfaces.specific.result.ResultLikeN`](index.html#returns.interfaces.specific.result.ResultLikeN "returns.interfaces.specific.result.ResultLikeN") or any other.

Summing up, decide what laws and methods you need to solve your problem.

And then subtype the interfaces that provide these methods and laws.

Example

What interfaces a `Pair` type needs?

* [`returns.interfaces.equable.Equable`](index.html#returns.interfaces.equable.Equable "returns.interfaces.equable.Equable"),

because two `Pair` instances can be compared

* [`returns.interfaces.mappable.MappableN`](index.html#returns.interfaces.mappable.MappableN "returns.interfaces.mappable.MappableN"),

because the first type can be composed with pure functions

* [`returns.interfaces.bindable.BindableN`](index.html#returns.interfaces.bindable.BindableN "returns.interfaces.bindable.BindableN"),

because a `Pair` can be bound to a function returning a new `Pair`

based on the first type

* [`returns.interfaces.altable.AltableN`](index.html#returns.interfaces.altable.AltableN "returns.interfaces.altable.AltableN"),

because the second type can be composed with pure functions

* [`returns.interfaces.lashable.LashableN`](index.html#returns.interfaces.lashable.LashableN "returns.interfaces.lashable.LashableN"),

because a `Pair` can be bound to a function returning a new `Pair`

based on the second type

Now, after we know about all interfaces we would need,

let’s find pre-defined aliases we can reuse.

Turns out, there are some of them!

* [`returns.interfaces.bimappable.BiMappableN`](index.html#returns.interfaces.bimappable.BiMappableN "returns.interfaces.bimappable.BiMappableN")

which combines `MappableN` and `AltableN`

* [`returns.interfaces.swappable.SwappableN`](index.html#returns.interfaces.swappable.SwappableN "returns.interfaces.swappable.SwappableN")

is an alias for `BiMappableN`

with a new method called `.swap` to change values order

Let’s look at the result:

Note

A special note on [`returns.primitives.container.BaseContainer`](index.html#returns.primitives.container.BaseContainer "returns.primitives.container.BaseContainer").

It is a very useful class with lots of pre-defined features, like:

immutability, better cloning, serialization, and comparison.

You can skip it if you wish, but it is highlighly recommended.

Later we will talk about an actual implementation of all required methods.

### Step 2: Initial implementation[¶](#step-2-initial-implementation "Permalink to this heading")

So, let’s start writing some code!

We would need to implement all interface methods,

otherwise `mypy` won’t be happy.

That’s what it currently says on our type definition:

```

error: Final class test\_pair1.Pair has abstract attributes "alt", "bind", "equals", "lash", "map", "swap"

```

Looks like it already knows what methods should be there!

Ok, let’s drop some initial and straight forward implementation.

We will later make it more complex step by step.

```

 1from typing import Callable, Tuple, TypeVar, final

 2

 3from returns.interfaces import bindable, equable, lashable, swappable

 4from returns.primitives.container import BaseContainer, container\_equality

 5from returns.primitives.hkt import Kind2, SupportsKind2, dekind

 6

 7\_FirstType = TypeVar('\_FirstType')

 8\_SecondType = TypeVar('\_SecondType')

 9

10\_NewFirstType = TypeVar('\_NewFirstType')

11\_NewSecondType = TypeVar('\_NewSecondType')

12

13

14@final

15class Pair(

16    BaseContainer,

17    SupportsKind2['Pair', \_FirstType, \_SecondType],

18    bindable.Bindable2[\_FirstType, \_SecondType],

19    swappable.Swappable2[\_FirstType, \_SecondType],

20    lashable.Lashable2[\_FirstType, \_SecondType],

21    equable.Equable,

22):

23 """

24 A type that represents a pair of something.

25

26 Like to coordinates ``(x, y)`` or two best friends.

27 Or a question and an answer.

28

29 """

30

31    def \_\_init\_\_(

32        self,

33        inner\_value: Tuple[\_FirstType, \_SecondType],

34    ) -> None:

35 """Saves passed tuple as ``.\_inner\_value`` inside this instance."""

36        super().\_\_init\_\_(inner\_value)

37

38    # `Equable` part:

39

40    equals = container\_equality  # we already have this defined for all types

41

42    # `Mappable` part via `BiMappable`:

43

44    def map(

45        self,

46        function: Callable[[\_FirstType], \_NewFirstType],

47    ) -> 'Pair[\_NewFirstType, \_SecondType]':

48        return Pair((function(self.\_inner\_value[0]), self.\_inner\_value[1]))

49

50    # `BindableN` part:

51

52    def bind(

53        self,

54        function: Callable[

55            [\_FirstType],

56            Kind2['Pair', \_NewFirstType, \_SecondType],

57        ],

58    ) -> 'Pair[\_NewFirstType, \_SecondType]':

59        return dekind(function(self.\_inner\_value[0]))

60

61    # `AltableN` part via `BiMappableN`:

62

63    def alt(

64        self,

65        function: Callable[[\_SecondType], \_NewSecondType],

66    ) -> 'Pair[\_FirstType, \_NewSecondType]':

67        return Pair((self.\_inner\_value[0], function(self.\_inner\_value[1])))

68

69    # `LashableN` part:

70

71    def lash(

72        self,

73        function: Callable[

74            [\_SecondType],

75            Kind2['Pair', \_FirstType, \_NewSecondType],

76        ],

77    ) -> 'Pair[\_FirstType, \_NewSecondType]':

78        return dekind(function(self.\_inner\_value[1]))

79

80    # `SwappableN` part:

81

82    def swap(self) -> 'Pair[\_SecondType, \_FirstType]':

83        return Pair((self.\_inner\_value[1], self.\_inner\_value[0]))

```

You can check our resulting source with `mypy`. It would be happy this time.

### Step 3: New interfaces[¶](#step-3-new-interfaces "Permalink to this heading")

As you can see our existing interfaces do not cover everything.

We can potentially want several extra things:

1. A method that takes two arguments and returns a new `Pair` instance

2. A named constructor to create a `Pair` from a single value

3. A named constructor to create a `Pair` from two values

We can define an interface just for this!

It would be also nice to add all other interfaces there as supertypes.

That’s how it is going to look:

```

 1class PairLikeN(

 2    bindable.BindableN[\_FirstType, \_SecondType, \_ThirdType],

 3    swappable.SwappableN[\_FirstType, \_SecondType, \_ThirdType],

 4    lashable.LashableN[\_FirstType, \_SecondType, \_ThirdType],

 5    equable.Equable,

 6):

 7 """Special interface for types that look like a ``Pair``."""

 8

 9    @abstractmethod

10    def pair(

11        self: \_PairLikeKind,

12        function: Callable[

13            [\_FirstType, \_SecondType],

14            KindN[\_PairLikeKind, \_NewFirstType, \_NewSecondType, \_ThirdType],

15        ],

16    ) -> KindN[\_PairLikeKind, \_NewFirstType, \_NewSecondType, \_ThirdType]:

17 """Allows to work with both arguments at the same time."""

18

19    @classmethod

20    @abstractmethod

21    def from\_paired(

22        cls: Type[\_PairLikeKind],

23        first: \_NewFirstType,

24        second: \_NewSecondType,

25    ) -> KindN[\_PairLikeKind, \_NewFirstType, \_NewSecondType, \_ThirdType]:

26 """Allows to create a PairLikeN from just two values."""

27

28    @classmethod

29    @abstractmethod

30    def from\_unpaired(

31        cls: Type[\_PairLikeKind],

32        inner\_value: \_NewFirstType,

33    ) -> KindN[\_PairLikeKind, \_NewFirstType, \_NewFirstType, \_ThirdType]:

34 """Allows to create a PairLikeN from just a single object."""

```

Awesome! Now we have a new interface to implement. Let’s do that!

```

1    def pair(

2        self,

3        function: Callable[

4            [\_FirstType, \_SecondType],

5            Kind2['Pair', \_NewFirstType, \_NewSecondType],

6        ],

7    ) -> 'Pair[\_NewFirstType, \_NewSecondType]':

8        return dekind(function(self.\_inner\_value[0], self.\_inner\_value[1]))

```

```

1    @classmethod

2    def from\_unpaired(

3        cls,

4        inner\_value: \_NewFirstType,

5    ) -> 'Pair[\_NewFirstType, \_NewFirstType]':

6        return Pair((inner\_value, inner\_value))

```

Looks like we are done!

### Step 4: Writing tests and docs[¶](#step-4-writing-tests-and-docs "Permalink to this heading")

The best part about this type is that it is pure.

So, we can write our tests inside docs!

We are going to use

[doctests](https://docs.python.org/3/library/doctest.html)

builtin module for that.

This gives us several key benefits:

* All our docs has usage examples

* All our examples are correct, because they are executed and tested

* We don’t need to write regular boring tests

Let’s add docs and doctests! Let’s use `map` method as a short example:

```

 1    def map(

 2        self,

 3        function: Callable[[\_FirstType], \_NewFirstType],

 4    ) -> 'Pair[\_NewFirstType, \_SecondType]':

 5 """

 6 Changes the first type with a pure function.

 7

 8 >>> assert Pair((1, 2)).map(str) == Pair(('1', 2))

 9

10 """

11        return Pair((function(self.\_inner\_value[0]), self.\_inner\_value[1]))

```

By adding these simple tests we would already have 100% coverage.

But, what if we can completely skip writing tests, but still have 100%?

Let’s discuss how we can achieve that with “Laws as values”.

### Step 5: Checking laws[¶](#step-5-checking-laws "Permalink to this heading")

We already ship lots of laws with our interfaces.

See our docs on [laws and checking them](index.html#hypothesis-plugins).

Moreover, you can also define your own laws!

Let’s add them to our `PairLikeN` interface.

Let’s start with laws definition:

```

 1class \_LawSpec(LawSpecDef):

 2    @law\_definition

 3    def pair\_equality\_law(

 4        raw\_value: \_FirstType,

 5        container: 'PairLikeN[\_FirstType, \_SecondType, \_ThirdType]',

 6    ) -> None:

 7 """Ensures that unpaired and paired constructors work fine."""

 8        assert\_equal(

 9            container.from\_unpaired(raw\_value),

10            container.from\_paired(raw\_value, raw\_value),

11        )

12

13    @law\_definition

14    def pair\_left\_identity\_law(

15        pair: Tuple[\_FirstType, \_SecondType],

16        container: 'PairLikeN[\_FirstType, \_SecondType, \_ThirdType]',

17        function: Callable[

18            [\_FirstType, \_SecondType],

19            KindN['PairLikeN', \_NewFirstType, \_NewSecondType, \_ThirdType],

20        ],

21    ) -> None:

22 """Ensures that unpaired and paired constructors work fine."""

23        assert\_equal(

24            container.from\_paired(\*pair).pair(function),

25            function(\*pair),

26        )

```

And them let’s add them to our `PairLikeN` interface:

```

 1class PairLikeN(

 2    bindable.BindableN[\_FirstType, \_SecondType, \_ThirdType],

 3    swappable.SwappableN[\_FirstType, \_SecondType, \_ThirdType],

 4    lashable.LashableN[\_FirstType, \_SecondType, \_ThirdType],

 5    equable.Equable,

 6):

 7 """Special interface for types that look like a ``Pair``."""

 8

 9 \_laws: ClassVar[Sequence[Law]] = (

10 Law2(\_LawSpec.pair\_equality\_law),

11 Law3(\_LawSpec.pair\_left\_identity\_law),

12 )

13

14    @abstractmethod

15    def pair(

16        self: \_PairLikeKind,

17        function: Callable[

18            [\_FirstType, \_SecondType],

19            KindN[\_PairLikeKind, \_NewFirstType, \_NewSecondType, \_ThirdType],

20        ],

21    ) -> KindN[\_PairLikeKind, \_NewFirstType, \_NewSecondType, \_ThirdType]:

22 """Allows to work with both arguments at the same time."""

23

24    @classmethod

25    @abstractmethod

26    def from\_paired(

27        cls: Type[\_PairLikeKind],

28        first: \_NewFirstType,

29        second: \_NewSecondType,

30    ) -> KindN[\_PairLikeKind, \_NewFirstType, \_NewSecondType, \_ThirdType]:

31 """Allows to create a PairLikeN from just two values."""

32

33    @classmethod

34    @abstractmethod

35    def from\_unpaired(

36        cls: Type[\_PairLikeKind],

37        inner\_value: \_NewFirstType,

38    ) -> KindN[\_PairLikeKind, \_NewFirstType, \_NewFirstType, \_ThirdType]:

39 """Allows to create a PairLikeN from just a single object."""

```

The last to do is to call `check\_all\_laws(Pair, use\_init=True)`

to generate 10 `hypothesis` test cases with hundreds real test cases inside.

Here’s the final result of our brand new `Pair` type:

```

 1from abc import abstractmethod

 2from typing import (

 3    Callable,

 4    ClassVar,

 5    NoReturn,

 6    Sequence,

 7    Tuple,

 8    Type,

 9    TypeVar,

 10    final,

 11)

 12

 13from returns.contrib.hypothesis.laws import check\_all\_laws

 14from returns.interfaces import bindable, equable, lashable, swappable

 15from returns.primitives.asserts import assert\_equal

 16from returns.primitives.container import BaseContainer, container\_equality

 17from returns.primitives.hkt import Kind2, KindN, SupportsKind2, dekind

 18from returns.primitives.laws import Law, Law2, Law3, LawSpecDef, law\_definition

 19

 20\_FirstType = TypeVar('\_FirstType')

 21\_SecondType = TypeVar('\_SecondType')

 22\_ThirdType = TypeVar('\_ThirdType')

 23

 24\_NewFirstType = TypeVar('\_NewFirstType')

 25\_NewSecondType = TypeVar('\_NewSecondType')

 26

 27\_PairLikeKind = TypeVar('\_PairLikeKind', bound='PairLikeN')

 28

 29

 30class \_LawSpec(LawSpecDef):

 31    @law\_definition

 32    def pair\_equality\_law(

 33        raw\_value: \_FirstType,

 34        container: 'PairLikeN[\_FirstType, \_SecondType, \_ThirdType]',

 35    ) -> None:

 36 """Ensures that unpaired and paired constructors work fine."""

 37        assert\_equal(

 38            container.from\_unpaired(raw\_value),

 39            container.from\_paired(raw\_value, raw\_value),

 40        )

 41

 42    @law\_definition

 43    def pair\_left\_identity\_law(

 44        pair: Tuple[\_FirstType, \_SecondType],

 45        container: 'PairLikeN[\_FirstType, \_SecondType, \_ThirdType]',

 46        function: Callable[

 47            [\_FirstType, \_SecondType],

 48            KindN['PairLikeN', \_NewFirstType, \_NewSecondType, \_ThirdType],

 49        ],

 50    ) -> None:

 51 """Ensures that unpaired and paired constructors work fine."""

 52        assert\_equal(

 53            container.from\_paired(\*pair).pair(function),

 54            function(\*pair),

 55        )

 56

 57

 58class PairLikeN(

 59    bindable.BindableN[\_FirstType, \_SecondType, \_ThirdType],

 60    swappable.SwappableN[\_FirstType, \_SecondType, \_ThirdType],

 61    lashable.LashableN[\_FirstType, \_SecondType, \_ThirdType],

 62    equable.Equable,

 63):

 64 """Special interface for types that look like a ``Pair``."""

 65

 66    \_laws: ClassVar[Sequence[Law]] = (

 67        Law2(\_LawSpec.pair\_equality\_law),

 68        Law3(\_LawSpec.pair\_left\_identity\_law),

 69    )

 70

 71    @abstractmethod

 72    def pair(

 73        self: \_PairLikeKind,

 74        function: Callable[

 75            [\_FirstType, \_SecondType],

 76            KindN[\_PairLikeKind, \_NewFirstType, \_NewSecondType, \_ThirdType],

 77        ],

 78    ) -> KindN[\_PairLikeKind, \_NewFirstType, \_NewSecondType, \_ThirdType]:

 79 """Allows to work with both arguments at the same time."""

 80

 81    @classmethod

 82    @abstractmethod

 83    def from\_paired(

 84        cls: Type[\_PairLikeKind],

 85        first: \_NewFirstType,

 86        second: \_NewSecondType,

 87    ) -> KindN[\_PairLikeKind, \_NewFirstType, \_NewSecondType, \_ThirdType]:

 88 """Allows to create a PairLikeN from just two values."""

 89

 90    @classmethod

 91    @abstractmethod

 92    def from\_unpaired(

 93        cls: Type[\_PairLikeKind],

 94        inner\_value: \_NewFirstType,

 95    ) -> KindN[\_PairLikeKind, \_NewFirstType, \_NewFirstType, \_ThirdType]:

 96 """Allows to create a PairLikeN from just a single object."""

 97

 98

 99PairLike2 = PairLikeN[\_FirstType, \_SecondType, NoReturn]

100PairLike3 = PairLikeN[\_FirstType, \_SecondType, \_ThirdType]

101

102

103@final

104class Pair(

105    BaseContainer,

106    SupportsKind2['Pair', \_FirstType, \_SecondType],

107    PairLike2[\_FirstType, \_SecondType],

108):

109 """

110 A type that represents a pair of something.

111

112 Like to coordinates ``(x, y)`` or two best friends.

113 Or a question and an answer.

114

115 """

116

117    def \_\_init\_\_(

118        self,

119        inner\_value: Tuple[\_FirstType, \_SecondType],

120    ) -> None:

121 """Saves passed tuple as ``.\_inner\_value`` inside this instance."""

122        super().\_\_init\_\_(inner\_value)

123

124    # `Equable` part:

125

126    equals = container\_equality  # we already have this defined for all types

127

128    # `Mappable` part via `BiMappable`:

129

130    def map(

131        self,

132        function: Callable[[\_FirstType], \_NewFirstType],

133    ) -> 'Pair[\_NewFirstType, \_SecondType]':

134 """

135 Changes the first type with a pure function.

136

137 >>> assert Pair((1, 2)).map(str) == Pair(('1', 2))

138

139 """

140        return Pair((function(self.\_inner\_value[0]), self.\_inner\_value[1]))

141

142    # `BindableN` part:

143

144    def bind(

145        self,

146        function: Callable[

147            [\_FirstType],

148            Kind2['Pair', \_NewFirstType, \_SecondType],

149        ],

150    ) -> 'Pair[\_NewFirstType, \_SecondType]':

151 """

152 Changes the first type with a function returning another ``Pair``.

153

154 >>> def bindable(first: int) -> Pair[str, str]:

155 ... return Pair((str(first), ''))

156

157 >>> assert Pair((1, 'b')).bind(bindable) == Pair(('1', ''))

158

159 """

160        return dekind(function(self.\_inner\_value[0]))

161

162    # `AltableN` part via `BiMappableN`:

163

164    def alt(

165        self,

166        function: Callable[[\_SecondType], \_NewSecondType],

167    ) -> 'Pair[\_FirstType, \_NewSecondType]':

168 """

169 Changes the second type with a pure function.

170

171 >>> assert Pair((1, 2)).alt(str) == Pair((1, '2'))

172

173 """

174        return Pair((self.\_inner\_value[0], function(self.\_inner\_value[1])))

175

176    # `LashableN` part:

177

178    def lash(

179        self,

180        function: Callable[

181            [\_SecondType],

182            Kind2['Pair', \_FirstType, \_NewSecondType],

183        ],

184    ) -> 'Pair[\_FirstType, \_NewSecondType]':

185 """

186 Changes the second type with a function returning ``Pair``.

187

188 >>> def lashable(second: int) -> Pair[str, str]:

189 ... return Pair(('', str(second)))

190

191 >>> assert Pair(('a', 2)).lash(lashable) == Pair(('', '2'))

192

193 """

194        return dekind(function(self.\_inner\_value[1]))

195

196    # `SwappableN` part:

197

198    def swap(self) -> 'Pair[\_SecondType, \_FirstType]':

199 """

200 Swaps ``Pair`` elements.

201

202 >>> assert Pair((1, 2)).swap() == Pair((2, 1))

203

204 """

205        return Pair((self.\_inner\_value[1], self.\_inner\_value[0]))

206

207    # `PairLikeN` part:

208

209    def pair(

210        self,

211        function: Callable[

212            [\_FirstType, \_SecondType],

213            Kind2['Pair', \_NewFirstType, \_NewSecondType],

214        ],

215    ) -> 'Pair[\_NewFirstType, \_NewSecondType]':

216 """

217 Creates a new ``Pair`` from an existing one via a passed function.

218

219 >>> def min\_max(first: int, second: int) -> Pair[int, int]:

220 ... return Pair((min(first, second), max(first, second)))

221

222 >>> assert Pair((2, 1)).pair(min\_max) == Pair((1, 2))

223 >>> assert Pair((1, 2)).pair(min\_max) == Pair((1, 2))

224

225 """

226        return dekind(function(self.\_inner\_value[0], self.\_inner\_value[1]))

227

228    @classmethod

229    def from\_paired(

230        cls,

231        first: \_NewFirstType,

232        second: \_NewSecondType,

233    ) -> 'Pair[\_NewFirstType, \_NewSecondType]':

234 """

235 Creates a new pair from two values.

236

237 >>> assert Pair.from\_paired(1, 2) == Pair((1, 2))

238

239 """

240        return Pair((first, second))

241

242    @classmethod

243    def from\_unpaired(

244        cls,

245        inner\_value: \_NewFirstType,

246    ) -> 'Pair[\_NewFirstType, \_NewFirstType]':

247 """

248 Creates a new pair from a single value.

249

250 >>> assert Pair.from\_unpaired(1) == Pair((1, 1))

251

252 """

253        return Pair((inner\_value, inner\_value))

254

255

256# Running hypothesis auto-generated tests:

257check\_all\_laws(Pair, use\_init=True)

```

### Step 6: Writing type-tests[¶](#step-6-writing-type-tests "Permalink to this heading")

Note

You can find all [type-tests here](https://github.com/dry-python/returns/tree/master/typesafety/test_examples).

The next thing we want is to write a type-test!

What is a type-test? This is a special type of tests for your typing.

We run `mypy` on top of tests and use snapshots to assert the result.

We recommend to use [pytest-mypy-plugins](https://github.com/typeddjango/pytest-mypy-plugins).

[Read more](https://sobolevn.me/2019/08/testing-mypy-types)

about how to use it.

Let’s start with a simple test

to make sure our `.pair` function works correctly:

Warning

Please, don’t use `env:` property the way we do here.

We need it since we store our example in `tests/` folder.

And we have to tell `mypy` how to find it.

```

 1- case: test\_pair\_type

 2  disable\_cache: false

 3  env:

 4    # We only need this because we store this example in `tests/`

 5    # and not in our source code. Please, do not copy this line!

 6    - MYPYPATH=./tests/test\_examples/test\_your\_container

 7

 8  # TODO: remove this config after

 9  # mypy/typeshed/stdlib/unittest/mock.pyi:120:

10  # error: Class cannot subclass "Any" (has type "Any")

11  # is fixed.

12  mypy\_config:

13    disallow\_subclassing\_any = False

14  main: |

15    # Let's import our `Pair` type we defined earlier:

16    from test\_pair4 import Pair

17

18    reveal\_type(Pair)

19

20    def function(first: int, second: str) -> Pair[float, bool]:

21        ...

22

23    my\_pair: Pair[int, str] = Pair.from\_paired(1, 'a')

24    reveal\_type(my\_pair.pair(function))

25  out: |

26    main:4: note: Revealed type is "def [\_FirstType, \_SecondType] (inner\_value: Tuple[\_FirstType`1, \_SecondType`2]) -> test\_pair4.Pair[\_FirstType`1, \_SecondType`2]"

27    main:10: note: Revealed type is "test\_pair4.Pair[builtins.float, builtins.bool]"

```

Ok, now, let’s try to raise an error by using it incorrectly:

```

 1- case: test\_pair\_error

 2  disable\_cache: false

 3  env:

 4    # We only need this because we store this example in `tests/`

 5    # and not in our source code. Please, do not copy this line!

 6    - MYPYPATH=./tests/test\_examples/test\_your\_container

 7

 8  # TODO: remove this config after

 9  # mypy/typeshed/stdlib/unittest/mock.pyi:120:

10  # error: Class cannot subclass "Any" (has type "Any")

11  # is fixed.

12  mypy\_config:

13    disallow\_subclassing\_any = False

14  main: |

15    # Let's import our `Pair` type we defined earlier:

16    from test\_pair4 import Pair

17

18    # Oups! This function has first and second types swapped!

19    def function(first: str, second: int) -> Pair[float, bool]:

20        ...

21

22    my\_pair = Pair.from\_paired(1, 'a')

23    my\_pair.pair(function)  # this should and will error

24  out: |

25    main:9: error: Argument 1 to "pair" of "Pair" has incompatible type "Callable[[str, int], Pair[float, bool]]"; expected "Callable[[int, str], KindN[Pair[Any, Any], float, bool, Any]]"  [arg-type]

```

### Step 7: Reusing code[¶](#step-7-reusing-code "Permalink to this heading")

The last (but not the least!) thing you need

to know is that you can reuse all code

we already have for this new `Pair` type.

This is because of our [Higher Kinded Types](index.html#hkt) feature.

So, let’s say we want to use native `map\_()`

pointfree function with our new `Pair` type.

Let’s test that it will work correctly:

```

 1- case: test\_pair\_map

 2  disable\_cache: false

 3  env:

 4    # We only need this because we store this example in `tests/`

 5    # and not in our source code. Please, do not copy this line!

 6    - MYPYPATH=./tests/test\_examples/test\_your\_container

 7

 8  # TODO: remove this config after

 9  # mypy/typeshed/stdlib/unittest/mock.pyi:120:

10  # error: Class cannot subclass "Any" (has type "Any")

11  # is fixed.

12  mypy\_config:

13    disallow\_subclassing\_any = False

14  main: |

15    from test\_pair4 import Pair

16    from returns.pointfree import map\_

17

18    my\_pair: Pair[int, int] = Pair.from\_unpaired(1)

19    reveal\_type(my\_pair.map(str))

20    reveal\_type(map\_(str)(my\_pair))

21  out: |

22    main:5: note: Revealed type is "test\_pair4.Pair[builtins.str, builtins.int]"

23    main:6: note: Revealed type is "test\_pair4.Pair[builtins.str, builtins.int]"

```

Yes, it works!

Now you have fully working, typed, documented, lawful, and tested primitive.

You can build any other primitive

you need for your business logic or infrastructure.

Pipelines[¶](#pipelines "Permalink to this heading")

----------------------------------------------------

The main idea behind functional programming is functional composition.

We provide several tools to make

composition easy, readable, pythonic, and useful.

Note

Make sure you are familiar with our [Pointfree](index.html#pointfree) tools,

because pipelines and pointfree functions are best friends!

### flow[¶](#flow "Permalink to this heading")

`flow` allows to easily compose multiple functions together into a pipeline.

It is useful when you already have an instance to compose functions with.

Note

`flow` is the recommended way to write your code with `returns`!

Let’s see an example:

```

>>> from returns.pipeline import flow

>>> assert flow(

...     [1, 2, 3],

...     lambda collection: max(collection),

...     lambda max\_number: -max\_number,

... ) == -3

```

This allows you to write declarative steps

that should be performed on an existing value.

Note

Technical note: `flow` has the best type inference mechanism

among all other tools we provide here.

This happens due to our [mypy plugins](index.html#mypy-plugins).

You can also use `flow` with pointfree functions and containers:

```

>>> from returns.result import Result, Success, Failure

>>> from returns.pointfree import bind

>>> from returns.pipeline import flow

>>> def regular\_function(arg: int) -> float:

...     return float(arg)

>>> def returns\_container(arg: float) -> Result[str, ValueError]:

...     if arg != 0:

...         return Success(str(arg))

...     return Failure(ValueError('Wrong arg'))

>>> def also\_returns\_container(arg: str) -> Result[str, ValueError]:

...     return Success(arg + '!')

>>> assert flow(

...     1,  # initial value

...     regular\_function,  # composes easily

...     returns\_container,  # also composes easily, but returns a container

...     # So we need to `bind` the next function to allow it to consume

...     # the container from the previous step.

...     bind(also\_returns\_container),

... ) == Success('1.0!')

>>> # And this will fail:

>>> assert flow(

...     0,  # initial value

...     regular\_function,  # composes easily

...     returns\_container,  # also composes easily, but returns a container

...     # So we need to `bind` the next function to allow it to consume

...     # the container from the previous step.

...     bind(also\_returns\_container),

... ).failure().args == ('Wrong arg', )

```

And now let’s get to know `pipe`, it is very similar,

but has different usage pattern.

### pipe[¶](#pipe "Permalink to this heading")

`pipe` is an easy way to compose functions together.

It is useful when you don’t have an instance to compose functions with yet.

Note

`pipe` requires to use our [mypy plugins](index.html#mypy-plugins).

Let’s see an example.

```

>>> from returns.pipeline import pipe

>>> pipeline = pipe(str, lambda x: x + 'b', str.upper)

>>> assert pipeline(1) == '1B'

```

It might be later used with multiple values:

```

>>> assert pipeline(2) == '2B'

```

It is also might be useful to compose containers together:

```

>>> from returns.pipeline import pipe

>>> from returns.result import Result, Success, Failure

>>> from returns.pointfree import bind

>>> def regular\_function(arg: int) -> float:

...     return float(arg)

>>> def returns\_container(arg: float) -> Result[str, ValueError]:

...     if arg != 0:

...         return Success(str(arg))

...     return Failure(ValueError('Wrong arg'))

>>> def also\_returns\_container(arg: str) -> Result[str, ValueError]:

...     return Success(arg + '!')

>>> transaction = pipe(

...     regular\_function,  # composes easily

...     returns\_container,  # also composes easily, but returns a container

...     # So we need to `bind` the next function to allow it to consume

...     # the container from the previous step.

...     bind(also\_returns\_container),

... )

>>> result = transaction(1)  # running the pipeline

>>> assert result == Success('1.0!')

```

You might consider `pipe()` as [`returns.functions.compose()`](index.html#returns.functions.compose "returns.functions.compose") on steroids.

The main difference is that `compose` takes strictly two arguments

(or you might say that it has an arity of two),

while `pipe` has infinite possible arguments.

### managed[¶](#managed "Permalink to this heading")

A really common task is to work with something stateful,

like database connections or files.

First, you need to acquire some resource,

then use it and do your thing,

and clear things up and release the acquired resource.

There are several rules here:

1. If the acquiring failed,

then do nothing: do not try to use the resource or release it

2. If the resource is acquired, then try to use it

and then release it despite of the usage result

In other words, if you cannot open a file, then do nothing.

If you opened it, then try to read it. And then always close it.

Let’s say you have to read a file’s contents:

```

>>> from typing import TextIO

>>> from returns.pipeline import managed, is\_successful

>>> from returns.result import ResultE

>>> from returns.io import IOResultE, impure\_safe

>>> def read\_file(file\_obj: TextIO) -> IOResultE[str]:

...     return impure\_safe(file\_obj.read)()  # this will be the final result

>>> def close\_file(

...     file\_obj: TextIO,

...     file\_contents: ResultE[str],

... ) -> IOResultE[None]:  # sometimes might require to use `untap`

...     return impure\_safe(file\_obj.close)()  # this value will be dropped

>>> managed\_read = managed(read\_file, close\_file)

>>> read\_result = managed\_read(

...     impure\_safe(lambda filename: open(filename, 'r'))('pyproject.toml'),

... )

>>> assert is\_successful(read\_result)  # file content is inside `IOSuccess`

```

And here’s how we recommend to combine

`managed` with other pipeline functions:

```

>>> import tomlkit

>>> from returns.pipeline import flow

>>> from returns.pointfree import bind\_result

>>> from returns.result import safe

>>> from returns.io import IOSuccess

>>> @safe

... def parse\_toml(file\_contents: str) -> dict:

...     return tomlkit.parse(file\_contents)

>>> @safe

... def get\_project\_name(parsed: dict) -> str:

...     return parsed['tool']['poetry']['name']

>>> pipeline\_result = flow(

...     'pyproject.toml',  # filename we work with

...     impure\_safe(lambda filename: open(filename, 'r')),

...     managed\_read,

...     bind\_result(parse\_toml),

...     bind\_result(get\_project\_name),

... )

>>> assert pipeline\_result == IOSuccess('returns')

```

Notice a few tricks here:

1. We use `managed` with and without `flow` here,

both are fine!

2. We have created a `managed\_read` managed function,

so we don’t need to specify it every time we want

to read a file in a functional way

3. We are using impure and pure operations inside the pipeline:

this helps us to understand how our app works.

Which parts do access the file system and which just work

However, you can still use the imperative approach

with `with:` or `try/finally` wrapped into `@impure\_safe` decorator,

your choice! We don’t recommend to mix these two.

Stick to one you like the most.

`managed` can be used with:

* `IOResult`

* `FutureResult`

* `RequiresContextIOResult`

* `RequiresContextFutureResult`

### is\_successful[¶](#is-successful "Permalink to this heading")

`is\_successful` is used to

tell whether or not your result is a success.

We treat only three types that do not throw as successful ones,

basically: [`Success`](index.html#returns.result.Success "returns.result.Success"),

[`IOSuccess`](index.html#returns.io.IOSuccess "returns.io.IOSuccess"),

and [`Some`](index.html#returns.maybe.Some "returns.maybe.Some")

```

>>> from returns.result import Success, Failure

>>> from returns.pipeline import is\_successful

>>> assert is\_successful(Success(1)) is True

>>> assert is\_successful(Failure('text')) is False

```

### Further reading[¶](#further-reading "Permalink to this heading")

* [fp-ts pipeable](https://github.com/gcanti/fp-ts/blob/master/src/pipeable.ts)

* [ZIO Managed](https://zio.dev/docs/datatypes/datatypes_managed)

### API Reference[¶](#api-reference "Permalink to this heading")

flow(*instance*, *\*functions*)[[source]](_modules/returns/_internal/pipeline/flow.html#flow)[¶](#returns.pipeline.flow "Permalink to this definition")

Allows to compose a value and up to multiple functions that use this value.

All starts with the value itself.

Each next function uses the previous result as an input parameter.

We use a custom `mypy` plugin to make sure types are correct.

Otherwise, it is currently impossible to properly type this function.

Currently, `flow` has a hard limit of 21 steps.

Because, it is not possible to type it otherwise.

We need a hard limit.

See: <https://github.com/dry-python/returns/issues/461>

Here’s how it should be used:

```

>>> from returns.pipeline import flow

>>> # => executes: str(float(int('1')))

>>> assert flow('1', int, float, str) == '1.0'

```

This function is closely related

to `pipe`:

```

>>> from returns.pipeline import pipe

>>> assert flow('1', int, float, str) == pipe(int, float, str)('1')

```

See also

* <https://stackoverflow.com/a/41585450/4842742>

* <https://github.com/gcanti/fp-ts/blob/master/src/pipeable.ts>

Requires our [mypy plugin](index.html#mypy-plugins).

Parameters:

* **instance** (`TypeVar`(`\_InstanceType`)) –

* **functions** (`TypeVar`(`\_PipelineStepType`)) –

Return type:

`TypeVar`(`\_ReturnType`)

pipe(*\*functions*)[[source]](_modules/returns/_internal/pipeline/pipe.html#pipe)[¶](#returns.pipeline.pipe "Permalink to this definition")

Allows to compose a value and up to 7 functions that use this value.

We use a custom `mypy` plugin to make sure types are correct.

Otherwise, it is currently impossible to properly type this function.

Each next function uses the previous result as an input parameter.

Here’s how it should be used:

```

>>> from returns.pipeline import pipe

>>> # => executes: str(float(int('1')))

>>> assert pipe(int, float, str)('1') == '1.0'

```

This function is closely related

to `pipe`:

```

>>> from returns.pipeline import flow

>>> assert pipe(int, float, str)('1') == flow('1', int, float, str)

```

See also

* <https://stackoverflow.com/a/41585450/4842742>

* <https://github.com/gcanti/fp-ts/blob/master/src/pipeable.ts>

managed(*use*, *release*)[[source]](_modules/returns/_internal/pipeline/managed.html#managed)[¶](#returns.pipeline.managed "Permalink to this definition")

Allows to run managed computation.

Managed computations consist of three steps:

1. `acquire` when we get some initial resource to work with

2. `use` when the main logic is done

3. `release` when we release acquired resource

Let’s look at the example:

1. We need to acquire an opened file to read it later

2. We need to use acquired file to read its content

3. We need to release the acquired file in the end

Here’s a code example:

```

>>> from returns.pipeline import managed

>>> from returns.io import IOSuccess, IOFailure, impure\_safe

>>> class Lock(object):

...  '''Example class to emulate state to acquire and release.'''

...     def \_\_init\_\_(self, default: bool = False) -> None:

...         self.set = default

...     def \_\_eq\_\_(self, lock) -> bool:  # we need this for testing

...         return self.set == lock.set

...     def release(self) -> None:

...         self.set = False

>>> pipeline = managed(

...     lambda lock: IOSuccess(lock) if lock.set else IOFailure(False),

...     lambda lock, use\_result: impure\_safe(lock.release)(),

... )

>>> assert pipeline(IOSuccess(Lock(True))) == IOSuccess(Lock(False))

>>> assert pipeline(IOSuccess(Lock())) == IOFailure(False)

>>> assert pipeline(IOFailure('no lock')) == IOFailure('no lock')

```

See also

* <https://github.com/gcanti/fp-ts/blob/master/src/IOEither.ts>

* <https://zio.dev/docs/datatypes/datatypes_managed>

Implementation

This class requires some explanation.

First of all, we modeled this function as a class,

so it can be partially applied easily.

Secondly, we used imperative approach of programming inside this class.

Functional approached was 2 times slower.

And way more complex to read and understand.

Lastly, we try to hide these two things for the end user.

We pretend that this is not a class, but a function.

We also do not break a functional abstraction for the end user.

It is just an implementation detail.

Type inference does not work so well with `lambda` functions.

But, we do not recommend to use this function with `lambda` functions.

Parameters:

* **use** (`Callable`[[`TypeVar`(`\_FirstType`)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_IOResultLikeType`, bound= [`IOResultLikeN`](index.html#returns.interfaces.specific.ioresult.IOResultLikeN "returns.interfaces.specific.ioresult.IOResultLikeN")), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]) –

* **release** (`Callable`[[`TypeVar`(`\_FirstType`), [`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_IOResultLikeType`, bound= [`IOResultLikeN`](index.html#returns.interfaces.specific.ioresult.IOResultLikeN "returns.interfaces.specific.ioresult.IOResultLikeN")), `None`, `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]) –

Return type:

[`Kinded`](index.html#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded")[`Callable`[[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_IOResultLikeType`, bound= [`IOResultLikeN`](index.html#returns.interfaces.specific.ioresult.IOResultLikeN "returns.interfaces.specific.ioresult.IOResultLikeN")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_IOResultLikeType`, bound= [`IOResultLikeN`](index.html#returns.interfaces.specific.ioresult.IOResultLikeN "returns.interfaces.specific.ioresult.IOResultLikeN")), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]]

is\_successful(*container*)[[source]](_modules/returns/pipeline.html#is_successful)[¶](#returns.pipeline.is_successful "Permalink to this definition")

Determines if a container was successful or not.

```

>>> from returns.maybe import Some, Nothing

>>> from returns.result import Failure, Success

>>> from returns.io import IOSuccess, IOFailure

>>> assert is\_successful(Some(1))

>>> assert not is\_successful(Nothing)

>>> assert is\_successful(Success(1))

>>> assert not is\_successful(Failure(1))

>>> assert is\_successful(IOSuccess(1))

>>> assert not is\_successful(IOFailure(1))

```

This function can work with containers

that are instance of [`returns.interfaces.unwrappable.Unwrappable`](index.html#returns.interfaces.unwrappable.Unwrappable "returns.interfaces.unwrappable.Unwrappable").

Parameters:

**container** ([`Unwrappable`](index.html#returns.interfaces.unwrappable.Unwrappable "returns.interfaces.unwrappable.Unwrappable")) – 

Return type:

`bool`

Converters[¶](#converters "Permalink to this heading")

------------------------------------------------------

We have several helpers to convert containers from one type to another

and back again.

### Maybe and Result[¶](#maybe-and-result "Permalink to this heading")

We have two converters to work with `Result <-> Maybe` transformations:

* [`maybe\_to\_result()`](#returns.converters.maybe_to_result "returns.converters.maybe_to_result") that converts `Maybe` to `Result`

* [`result\_to\_maybe()`](#returns.converters.result_to_maybe "returns.converters.result_to_maybe") that converts `Result` to `Maybe`

That’s how they work:

```

>>> from returns.converters import maybe\_to\_result, result\_to\_maybe

>>> from returns.maybe import Maybe, Some

>>> from returns.result import Result, Success

>>> result: Result[int, Exception] = Success(1)

>>> maybe: Maybe[int] = result\_to\_maybe(result)

>>> assert maybe == Some(1)

>>> new\_result: Result[int, None] = maybe\_to\_result(maybe)

>>> assert new\_result == Success(1)

```

Take a note, that type changes.

Also, take a note that `Success(None)` will be converted to `Nothing`.

### flatten[¶](#flatten "Permalink to this heading")

You can also use

[`flatten`](#returns.converters.flatten "returns.converters.flatten")

to merge nested containers together:

```

>>> from returns.converters import flatten

>>> from returns.maybe import Some

>>> from returns.result import Success

>>> from returns.io import IO

>>> assert flatten(IO(IO(1))) == IO(1)

>>> assert flatten(Some(Some(1))) == Some(1)

>>> assert flatten(Success(Success(1))) == Success(1)

```

### API Reference[¶](#module-returns.converters "Permalink to this heading")

flatten(*container*)[[source]](_modules/returns/converters.html#flatten)[¶](#returns.converters.flatten "Permalink to this definition")

Joins two nested containers together.

Please, note that it will not join

two `Failure` for `Result` case

or two `Nothing` for `Maybe` case

(or basically any two error types) together.

```

>>> from returns.converters import flatten

>>> from returns.io import IO

>>> from returns.result import Failure, Success

>>> assert flatten(IO(IO(1))) == IO(1)

>>> assert flatten(Success(Success(1))) == Success(1)

>>> assert flatten(Failure(Failure(1))) == Failure(Failure(1))

```

See also

* <https://bit.ly/2sIviUr>

Parameters:

**container** ([`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_BindableKind`, bound= [`BindableN`](index.html#returns.interfaces.bindable.BindableN "returns.interfaces.bindable.BindableN")), [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_BindableKind`, bound= [`BindableN`](index.html#returns.interfaces.bindable.BindableN "returns.interfaces.bindable.BindableN")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)], `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) – 

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_BindableKind`, bound= [`BindableN`](index.html#returns.interfaces.bindable.BindableN "returns.interfaces.bindable.BindableN")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

result\_to\_maybe(*result\_container*)[[source]](_modules/returns/converters.html#result_to_maybe)[¶](#returns.converters.result_to_maybe "Permalink to this definition")

Converts `Result` container to `Maybe` container.

```

>>> from returns.maybe import Some, Nothing

>>> from returns.result import Failure, Success

>>> assert result\_to\_maybe(Success(1)) == Some(1)

>>> assert result\_to\_maybe(Success(None)) == Some(None)

>>> assert result\_to\_maybe(Failure(1)) == Nothing

>>> assert result\_to\_maybe(Failure(None)) == Nothing

```

Parameters:

**result\_container** ([`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`)]) – 

Return type:

[`Maybe`](index.html#returns.maybe.Maybe "returns.maybe.Maybe")[`TypeVar`(`\_FirstType`)]

maybe\_to\_result(*maybe\_container*)[[source]](_modules/returns/converters.html#maybe_to_result)[¶](#returns.converters.maybe_to_result "Permalink to this definition")

Converts `Maybe` container to `Result` container.

```

>>> from returns.maybe import Some, Nothing

>>> from returns.result import Failure, Success

>>> assert maybe\_to\_result(Some(1)) == Success(1)

>>> assert maybe\_to\_result(Some(None)) == Success(None)

>>> assert maybe\_to\_result(Nothing) == Failure(None)

```

Parameters:

**maybe\_container** ([`Maybe`](index.html#returns.maybe.Maybe "returns.maybe.Maybe")[`TypeVar`(`\_FirstType`)]) – 

Return type:

[`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_FirstType`), `None`]

Pointfree[¶](#pointfree "Permalink to this heading")

----------------------------------------------------

This module provides a bunch of primitives to work with containers.

It makes composing functions with containers easier.

Sometimes using methods on containers is not very helpful.

Container methods are difficult to compose with other functions

or methods.

Instead we can use functions that produce the same result but have

the reverse semantics.

Usually, this means changing something like `x.f(y)` to `f(x)(y)`.

Why would anyone need these functions when you can use methods?

To create pipelines!

```

from returns.pipeline import pipe

from returns.result import ResultE

def returns\_result(arg: int) -> ResultE[int]:

    ...

def works\_with\_result(arg: int) -> ResultE[int]:

    ...

def finish\_work(arg: int) -> ResultE[int]:

    ...

pipe(

    returns\_result,

    works\_with\_result,  # does not compose! Needs a container for input

    finish\_work,  # does not compose either!

)

```

Without pointfree functions you would probably have to write:

```

returns\_result().bind(works\_with\_result).bind(notifies\_user)

```

And you need a way to somehow do this in the pipeline syntax.

Remember that pipeline syntax helps make composing functions more readable

and pythonic.

That’s where pointfree functions become really useful.

### [map](#map)[¶](#map "Permalink to this heading")

`map\_()` is a pointfree alternative to the container method `.map()`.

It lifts a function to work from container to container. `map\_(f)`

would return f lifted to work on a container.

In other words, it modifies the function’s signature from:

`a -> b`

to:

`Container[a] -> Container[b]`

Doing this lets us compose regular functions and containers.

```

>>> from returns.pointfree import map\_

>>> from returns.maybe import Maybe, Some

>>> def as\_int(arg: str) -> int:

...     return ord(arg)

>>> container: Maybe[str] = Some('a')

>>> # We now have two ways to compose container and as\_int

>>> # 1. Via ``.map()``:

>>> assert container.map(as\_int) == Some(97)

>>> # 2. Or via ``map\_()``, like above but in the reverse order:

>>> assert map\_(as\_int)(container) == Some(97)

```

This means we can compose functions in a pipeline.

```

>>> from returns.pointfree import map\_

>>> from returns.pipeline import flow

>>> from returns.maybe import Maybe, Some, Nothing

>>> def index\_of\_7(arg: str) -> Maybe[int]:

...     if '7' in arg:

...         return Some(arg.index('7'))

...     return Nothing

>>> def double(num: int) -> int:

...     return num \* 2

>>> assert flow(

...     '007',

...     index\_of\_7,    # Some(2)

...     map\_(double),  # Some(4)

... ) == Some(4)

>>> # Still passes along Nothing

>>> assert flow(

...     '006',

...     index\_of\_7,    # Nothing

...     map\_(double),  # Nothing

... ) == Nothing

```

### bind[¶](#bind "Permalink to this heading")

Pointfree `bind()` is an alternative to the container method `.bind()`.

It binds a function that returns a container so that is accepts the same

container type as input.

In other words, it modifies the function’s signature from:

`a -> Container[b]`

to:

`Container[a] -> Container[b]`

Without `bind()` it would be very hard to declaratively compose two entities:

1. Existing containers

2. Existing functions that accept a regular value and return a container

We can compose these entities with `.bind()` when calling it on a container,

but how can we do it independently?

```

>>> from returns.pointfree import bind

>>> from returns.maybe import Maybe, Some

>>> def index\_of\_1(arg: str) -> Maybe[int]:

...     if '1' in arg:

...         return Some(arg.index('1'))

...     return Nothing

>>> container = Some('A1 Steak Sauce')

>>> # We now have two way of composing these entities.

>>> # 1. Via ``.bind``:

>>> assert container.bind(index\_of\_1) == Some(1)

>>> # 2. Or via the ``bind`` function.

>>> assert bind(index\_of\_1)(container) == Some(1)

>>> # This produces the same result, but in a different order

```

That’s it!

We also have a long list of other `bind\_\*` functions, like:

* `bind\_io` to bind functions returning `IO` container

* `bind\_result` to bind functions returning `Result` container

* `bind\_ioresult` to bind functions returning `IOResult` container

* `bind\_future` to bind functions returning `Future` container

* `bind\_async\_future` to bind async functions returning `Future` container

* `bind\_future\_result` to bind functions returning `FutureResult` container

* `bind\_async\_future\_result` to bind async functions

returning `FutureResult` container

* `bind\_context` to bind functions returning `RequiresContext` container

* `bind\_context\_result` to bind functions

returning `RequiresContextResult` container

* `bind\_context\_ioresult` to bind functions

returning `RequiresContextIOResult` container

* `bind\_async` to bind async functions

returning `Future` or `FutureResult`

* `bind\_awaitable` to bind async non-container functions

### alt[¶](#alt "Permalink to this heading")

Pointfree `alt()` is an alternative to the container method `.alt()`.

It lifts a function to act on the error contents of a container.

In other words, it modifies the function’s signature from:

`a -> b`

to:

`Container[\_, a] -> Container[\_, b]`

You can think of it like `map`, but for the second type of a container.

```

>>> from returns.io import IOFailure, IOSuccess

>>> from returns.pointfree import alt

>>> def half\_as\_bad(error\_code: int) -> float:

...     return error\_code / 2

>>> # When acting on a successful state, nothing happens.

>>> assert alt(half\_as\_bad)(IOSuccess(1)) == IOSuccess(1)

>>> # When acting on a failed state, the result changes

>>> assert alt(half\_as\_bad)(IOFailure(4)) == IOFailure(2.0)

>>> # This is equivalent to IOFailure(4).alt(half\_as\_bad)

>>> assert alt(half\_as\_bad)(IOFailure(4)) == IOFailure(4).alt(half\_as\_bad)

```

This inverse syntax lets us easily compose functions in a pipeline

```

>>> from returns.io import IOFailure, IOSuccess, IOResult

>>> from returns.pointfree import alt

>>> def always\_errors(user\_input: str) -> IOResult:

...     return IOFailure(len(user\_input))

>>> def twice\_as\_bad(exit\_code: int) -> int:

...     return exit\_code \* 2

>>> def make\_error\_message(exit\_code: int) -> str:

...     return 'Badness level: {0}'.format(exit\_code)

>>> assert flow(

...     '12345',

...     always\_errors,

...     alt(twice\_as\_bad),

...     alt(make\_error\_message)

... ) == IOFailure('Badness level: 10')

```

### lash[¶](#lash "Permalink to this heading")

Pointfree `lash()` function is an alternative

to `.lash()` container method.

It allows better composition by lifting a function that returns a

container to act on the failed state of a container.

You can think of it like `bind`, but for the second type of a container.

```

>>> from returns.pointfree import lash

>>> from returns.result import Success, Failure, Result

>>> def always\_succeeds(arg: str) -> Result[int, str]:

...     return Success(1)

>>> failed: Result[int, str] = Failure('a')

>>> # We now have two way of composing these entities.

>>> # 1. Via ``.lash``:

>>> assert failed.lash(always\_succeeds) == Success(1)

>>> # 2. Or via ``lash`` function, the same but in the inverse way:

>>> assert lash(always\_succeeds)(failed) == Success(1)

```

### apply[¶](#apply "Permalink to this heading")

Pointfree `apply` function allows

to use `.apply()` container method like a function:

```

>>> from returns.pointfree import apply

>>> from returns.maybe import Some, Nothing

>>> def wow(arg: int) -> str:

...     return chr(arg) + '!'

>>> assert apply(Some(wow))(Some(97)) == Some('a!')

>>> assert apply(Some(wow))(Some(98)) == Some('b!')

>>> assert apply(Some(wow))(Nothing) == Nothing

>>> assert apply(Nothing)(Nothing) == Nothing

```

If you wish to use `apply` inside a pipeline

here’s how it might look:

```

>>> from returns.pointfree import apply

>>> from returns.pipeline import flow

>>> from returns.maybe import Some, Nothing, Maybe

>>> from typing import Callable

>>> def wow(arg: int) -> str:

...     return chr(arg) + '!'

>>> def my\_response(is\_excited: bool) -> Maybe[Callable[[int], str]]:

...     if is\_excited:

...         return Some(wow)

...     return Nothing

>>> assert flow(

...     Some(97),

...     apply(my\_response(True)),

... ) == Some('a!')

>>> assert flow(

...     Nothing,

...     apply(my\_response(False)),

... ) == Nothing

```

Or with a function as the first parameter:

```

>>> from returns.pipeline import flow

>>> from returns.curry import curry

>>> from returns.maybe import Some

>>> @curry

... def add\_curried(first: int, second: int) -> int:

...     return first + second

>>> assert flow(

...     Some(add\_curried),

...     Some(2).apply,

...     Some(3).apply,

... ) == Some(5)

```

### compose\_result[¶](#compose-result "Permalink to this heading")

Sometimes we need to manipulate the inner `Result` of some containers like

`IOResult` or `FutureResult`. With `compose\_result` we can do this

kind of manipulation.

```

>>> from returns.pointfree import compose\_result

>>> from returns.io import IOResult, IOSuccess, IOFailure

>>> from returns.result import Result

>>> def cast\_to\_str(container: Result[float, int]) -> IOResult[str, int]:

...     return IOResult.from\_result(container.map(str))

>>> assert compose\_result(cast\_to\_str)(IOSuccess(42.0)) == IOSuccess('42.0')

>>> assert compose\_result(cast\_to\_str)(IOFailure(1)) == IOFailure(1)

```

### cond[¶](#cond "Permalink to this heading")

Sometimes we need to create `SingleFailableN` or `DiverseFailableN`

containers (e.g. `Maybe`, `ResultLikeN`) based on a boolean expression,

`cond` can help us.

Consider `cond` to be a functional `if`.

See the example below:

```

>>> from returns.pipeline import flow

>>> from returns.pointfree import cond

>>> from returns.result import Result, Failure, Success

>>> def returns\_boolean(arg: int) -> bool:

...     return bool(arg)

>>> assert flow(

...     returns\_boolean(1),

...     cond(Result, 'success', 'failure')

... ) == Success('success')

>>> assert flow(

...     returns\_boolean(0),

...     cond(Result, 'success', 'failure')

... ) == Failure('failure')

```

Example using `cond` with the `Maybe` container:

```

>>> from returns.pipeline import flow

>>> from returns.pointfree import cond

>>> from returns.maybe import Maybe, Some, Nothing

>>> assert flow(

...     returns\_boolean(1),

...     cond(Maybe, 'success')

... ) == Some('success')

>>> assert flow(

...     returns\_boolean(0),

...     cond(Maybe, 'success')

... ) == Nothing

```

### Further reading[¶](#further-reading "Permalink to this heading")

* [Tacit programming or point-free style](https://en.wikipedia.org/wiki/Tacit_programming)

* [Pointfree in Haskell](https://wiki.haskell.org/Pointfree)

### API Reference[¶](#api-reference "Permalink to this heading")

map\_(*function*)[[source]](_modules/returns/pointfree/map.html#map_)[¶](#returns.pointfree.map_ "Permalink to this definition")

Lifts function to be wrapped in a container for better composition.

In other words, it modifies the function’s

signature from:

`a -> b`

to: `Container[a] -> Container[b]`

This is how it should be used:

```

>>> from returns.io import IO

>>> from returns.pointfree import map\_

>>> def example(argument: int) -> float:

...     return argument / 2

>>> assert map\_(example)(IO(1)) == IO(0.5)

```

Note, that this function works for all containers with `.map` method.

See `returns.primitives.interfaces.mappable.MappableN` for more info.

See also

* <https://wiki.haskell.org/Lifting>

Parameters:

**function** (`Callable`[[`TypeVar`(`\_FirstType`)], `TypeVar`(`\_UpdatedType`)]) – 

Return type:

[`Kinded`](index.html#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded")[`Callable`[[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_MappableKind`, bound= [`MappableN`](index.html#returns.interfaces.mappable.MappableN "returns.interfaces.mappable.MappableN")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_MappableKind`, bound= [`MappableN`](index.html#returns.interfaces.mappable.MappableN "returns.interfaces.mappable.MappableN")), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]]

bind(*function*)[[source]](_modules/returns/pointfree/bind.html#bind)[¶](#returns.pointfree.bind "Permalink to this definition")

Turns function’s input parameter from a regular value to a container.

In other words, it modifies the function

signature from:

`a -> Container[b]`

to:

`Container[a] -> Container[b]`

Similar to [`returns.pointfree.lash()`](#returns.pointfree.lash "returns.pointfree.lash"),

but works for successful containers.

This is how it should be used:

```

>>> from returns.pointfree import bind

>>> from returns.maybe import Maybe, Some, Nothing

>>> def example(argument: int) -> Maybe[int]:

...     return Some(argument + 1)

>>> assert bind(example)(Some(1)) == Some(2)

>>> assert bind(example)(Nothing) == Nothing

```

Note, that this function works for all containers with `.bind` method.

See `returns.primitives.interfaces.bindable.BindableN` for more info.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_FirstType`)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_BindableKind`, bound= [`BindableN`](index.html#returns.interfaces.bindable.BindableN "returns.interfaces.bindable.BindableN")), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]) – 

Return type:

[`Kinded`](index.html#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded")[`Callable`[[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_BindableKind`, bound= [`BindableN`](index.html#returns.interfaces.bindable.BindableN "returns.interfaces.bindable.BindableN")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_BindableKind`, bound= [`BindableN`](index.html#returns.interfaces.bindable.BindableN "returns.interfaces.bindable.BindableN")), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]]

bind\_result(*function*)[[source]](_modules/returns/pointfree/bind_result.html#bind_result)[¶](#returns.pointfree.bind_result "Permalink to this definition")

Composes successful container with a function that returns a container.

In other words, it modifies the function’s

signature from:

`a -> Result[b, c]`

to:

`Container[a, c] -> Container[b, c]`

```

>>> from returns.io import IOSuccess

>>> from returns.context import RequiresContextResult

>>> from returns.result import Result, Success

>>> from returns.pointfree import bind\_result

>>> def returns\_result(arg: int) -> Result[int, str]:

...     return Success(arg + 1)

>>> bound = bind\_result(returns\_result)

>>> assert bound(IOSuccess(1)) == IOSuccess(2)

>>> assert bound(RequiresContextResult.from\_value(1))(...) == Success(2)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_FirstType`)], [`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`)]]) – 

Return type:

[`Kinded`](index.html#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded")[`Callable`[[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ResultLikeKind`, bound= [`ResultLikeN`](index.html#returns.interfaces.specific.result.ResultLikeN "returns.interfaces.specific.result.ResultLikeN")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ResultLikeKind`, bound= [`ResultLikeN`](index.html#returns.interfaces.specific.result.ResultLikeN "returns.interfaces.specific.result.ResultLikeN")), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]]

bind\_io(*function*)[[source]](_modules/returns/pointfree/bind_io.html#bind_io)[¶](#returns.pointfree.bind_io "Permalink to this definition")

Composes successful container with a function that returns a container.

In other words, it modifies the function’s

signature from:

`a -> IO[b]`

to:

`Container[a, c] -> Container[b, c]`

```

>>> from returns.io import IOSuccess, IOFailure

>>> from returns.io import IO

>>> from returns.pointfree import bind\_io

>>> def returns\_io(arg: int) -> IO[int]:

...     return IO(arg + 1)

>>> bound = bind\_io(returns\_io)

>>> assert bound(IO(1)) == IO(2)

>>> assert bound(IOSuccess(1)) == IOSuccess(2)

>>> assert bound(IOFailure(1)) == IOFailure(1)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_FirstType`, contravariant=True)], [`IO`](index.html#returns.io.IO "returns.io.IO")[`TypeVar`(`\_UpdatedType`, covariant=True)]]) – 

Return type:

[`Kinded`](index.html#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded")[`Callable`[[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_IOLikeKind`, bound= [`IOLikeN`](index.html#returns.interfaces.specific.io.IOLikeN "returns.interfaces.specific.io.IOLikeN")), `TypeVar`(`\_FirstType`, contravariant=True), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`, contravariant=True)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_IOLikeKind`, bound= [`IOLikeN`](index.html#returns.interfaces.specific.io.IOLikeN "returns.interfaces.specific.io.IOLikeN")), `TypeVar`(`\_UpdatedType`, covariant=True), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`, contravariant=True)]]]

bind\_ioresult(*function*)[[source]](_modules/returns/pointfree/bind_ioresult.html#bind_ioresult)[¶](#returns.pointfree.bind_ioresult "Permalink to this definition")

Composes successful container with a function that returns a container.

In other words, it modifies the function’s

signature from:

`a -> IOResult[b, c]`

to:

`Container[a, c] -> Container[b, c]`

```

>>> from returns.io import IOResult, IOSuccess

>>> from returns.context import RequiresContextIOResult

>>> from returns.pointfree import bind\_ioresult

>>> def returns\_ioresult(arg: int) -> IOResult[int, str]:

...     return IOSuccess(arg + 1)

>>> bound = bind\_ioresult(returns\_ioresult)

>>> assert bound(IOSuccess(1)) == IOSuccess(2)

>>> assert bound(

...     RequiresContextIOResult.from\_value(1),

... )(...) == IOSuccess(2)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_FirstType`)], [`IOResult`](index.html#returns.io.IOResult "returns.io.IOResult")[`TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`)]]) – 

Return type:

[`Kinded`](index.html#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded")[`Callable`[[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_IOResultLikeKind`, bound= [`IOResultLikeN`](index.html#returns.interfaces.specific.ioresult.IOResultLikeN "returns.interfaces.specific.ioresult.IOResultLikeN")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_IOResultLikeKind`, bound= [`IOResultLikeN`](index.html#returns.interfaces.specific.ioresult.IOResultLikeN "returns.interfaces.specific.ioresult.IOResultLikeN")), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]]

bind\_future(*function*)[[source]](_modules/returns/pointfree/bind_future.html#bind_future)[¶](#returns.pointfree.bind_future "Permalink to this definition")

Compose a container and sync function returning `Future`.

In other words, it modifies the function

signature from:

`a -> Future[b]`

to:

`Container[a] -> Container[b]`

Similar to [`returns.pointfree.lash()`](#returns.pointfree.lash "returns.pointfree.lash"),

but works for successful containers.

This is how it should be used:

```

>>> import anyio

>>> from returns.pointfree import bind\_future

>>> from returns.future import Future

>>> from returns.io import IO

>>> def example(argument: int) -> Future[int]:

...     return Future.from\_value(argument + 1)

>>> assert anyio.run(

...     bind\_future(example)(Future.from\_value(1)).awaitable,

... ) == IO(2)

```

Note, that this function works

for all containers with `.bind\_future` method.

See `returns.primitives.interfaces.specific.future.FutureLikeN`

for more info.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_FirstType`)], [`Future`](index.html#returns.future.Future "returns.future.Future")[`TypeVar`(`\_UpdatedType`)]]) – 

Return type:

[`Kinded`](index.html#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded")[`Callable`[[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_FutureKind`, bound= [`FutureLikeN`](index.html#returns.interfaces.specific.future.FutureLikeN "returns.interfaces.specific.future.FutureLikeN")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_FutureKind`, bound= [`FutureLikeN`](index.html#returns.interfaces.specific.future.FutureLikeN "returns.interfaces.specific.future.FutureLikeN")), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]]

bind\_async\_future(*function*)[[source]](_modules/returns/pointfree/bind_async_future.html#bind_async_future)[¶](#returns.pointfree.bind_async_future "Permalink to this definition")

Compose a container and async function returning `Future`.

In other words, it modifies the function

signature from:

`a -> Awaitable[Future[b]]`

to:

`Container[a] -> Container[b]`

This is how it should be used:

```

>>> import anyio

>>> from returns.pointfree import bind\_async\_future

>>> from returns.future import Future

>>> from returns.io import IO

>>> async def example(argument: int) -> Future[int]:

...     return Future.from\_value(argument + 1)

>>> assert anyio.run(

...     bind\_async\_future(example)(Future.from\_value(1)).awaitable,

... ) == IO(2)

```

Note, that this function works

for all containers with `.bind\_async\_future` method.

See `returns.primitives.interfaces.specific.future.FutureLikeN`

for more info.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_FirstType`)], `Awaitable`[[`Future`](index.html#returns.future.Future "returns.future.Future")[`TypeVar`(`\_UpdatedType`)]]]) – 

Return type:

[`Kinded`](index.html#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded")[`Callable`[[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_FutureKind`, bound= [`FutureLikeN`](index.html#returns.interfaces.specific.future.FutureLikeN "returns.interfaces.specific.future.FutureLikeN")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_FutureKind`, bound= [`FutureLikeN`](index.html#returns.interfaces.specific.future.FutureLikeN "returns.interfaces.specific.future.FutureLikeN")), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]]

bind\_future\_result(*function*)[[source]](_modules/returns/pointfree/bind_future_result.html#bind_future_result)[¶](#returns.pointfree.bind_future_result "Permalink to this definition")

Compose a container and async function returning `FutureResult`.

In other words, it modifies the function

signature from:

`a -> FutureResult[b, c]`

to:

`Container[a, c] -> Container[b, c]`

This is how it should be used:

```

>>> import anyio

>>> from returns.pointfree import bind\_future\_result

>>> from returns.future import FutureResult

>>> from returns.io import IOSuccess, IOFailure

>>> def example(argument: int) -> FutureResult[int, str]:

...     return FutureResult.from\_value(argument + 1)

>>> assert anyio.run(

...     bind\_future\_result(example)(

...         FutureResult.from\_value(1),

...     ).awaitable,

... ) == IOSuccess(2)

>>> assert anyio.run(

...     bind\_future\_result(example)(

...         FutureResult.from\_failure('a'),

...     ).awaitable,

... ) == IOFailure('a')

```

Note, that this function works

for all containers with `.bind\_async\_future` method.

See `FutureResultLikeN` for more info.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_FirstType`)], [`FutureResult`](index.html#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`)]]) – 

Return type:

[`Kinded`](index.html#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded")[`Callable`[[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_FutureResultKind`, bound= [`FutureResultLikeN`](index.html#returns.interfaces.specific.future_result.FutureResultLikeN "returns.interfaces.specific.future_result.FutureResultLikeN")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_FutureResultKind`, bound= [`FutureResultLikeN`](index.html#returns.interfaces.specific.future_result.FutureResultLikeN "returns.interfaces.specific.future_result.FutureResultLikeN")), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]]

bind\_async\_future\_result(*function*)[[source]](_modules/returns/pointfree/bind_async_future_result.html#bind_async_future_result)[¶](#returns.pointfree.bind_async_future_result "Permalink to this definition")

Compose a container and async function returning `FutureResult`.

In other words, it modifies the function

signature from:

`a -> Awaitable[FutureResult[b, c]]`

to:

`Container[a, c] -> Container[b, c]`

This is how it should be used:

```

>>> import anyio

>>> from returns.pointfree import bind\_async\_future\_result

>>> from returns.future import FutureResult

>>> from returns.io import IOSuccess, IOFailure

>>> async def example(argument: int) -> FutureResult[int, str]:

...     return FutureResult.from\_value(argument + 1)

>>> assert anyio.run(

...     bind\_async\_future\_result(example)(

...         FutureResult.from\_value(1),

...     ).awaitable,

... ) == IOSuccess(2)

>>> assert anyio.run(

...     bind\_async\_future\_result(example)(

...         FutureResult.from\_failure('a'),

...     ).awaitable,

... ) == IOFailure('a')

```

Note, that this function works

for all containers with `.bind\_async\_future` method.

See `FutureResultLikeN` for more info.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_FirstType`)], `Awaitable`[[`FutureResult`](index.html#returns.future.FutureResult "returns.future.FutureResult")[`TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`)]]]) – 

Return type:

[`Kinded`](index.html#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded")[`Callable`[[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_FutureResultKind`, bound= [`FutureResultLikeN`](index.html#returns.interfaces.specific.future_result.FutureResultLikeN "returns.interfaces.specific.future_result.FutureResultLikeN")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_FutureResultKind`, bound= [`FutureResultLikeN`](index.html#returns.interfaces.specific.future_result.FutureResultLikeN "returns.interfaces.specific.future_result.FutureResultLikeN")), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]]

bind\_context2(*function*)[[source]](_modules/returns/pointfree/bind_context.html#bind_context2)[¶](#returns.pointfree.bind_context2 "Permalink to this definition")

Composes successful container with a function that returns a container.

In other words, it modifies the function’s

signature from:

`a -> RequresContext[b, c]`

to:

`Container[a, c] -> Container[b, c]`

```

>>> from returns.pointfree import bind\_context2

>>> from returns.context import Reader

>>> def example(argument: int) -> Reader[int, int]:

...     return Reader(lambda deps: argument + deps)

>>> assert bind\_context2(example)(Reader.from\_value(2))(3) == 5

```

Note, that this function works with only `Kind2` containers

with `.bind\_context` method.

See `returns.primitives.interfaces.specific.reader.ReaderLike2`

for more info.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_FirstType`)], [`RequiresContext`](index.html#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[`TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`)]]) – 

Return type:

[`Kinded`](index.html#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded")[`Callable`[[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_Reader2Kind`, bound= [`ReaderLike2`](index.html#returns.interfaces.specific.reader.ReaderLike2 "returns.interfaces.specific.reader.ReaderLike2")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `Any`]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_Reader2Kind`, bound= [`ReaderLike2`](index.html#returns.interfaces.specific.reader.ReaderLike2 "returns.interfaces.specific.reader.ReaderLike2")), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `Any`]]]

bind\_context3(*function*)[[source]](_modules/returns/pointfree/bind_context.html#bind_context3)[¶](#returns.pointfree.bind_context3 "Permalink to this definition")

Composes successful container with a function that returns a container.

In other words, it modifies the function’s

signature from: `a -> RequresContext[b, c]`

to: `Container[a, c] -> Container[b, c]`

```

>>> from returns.context import RequiresContext, RequiresContextResult

>>> from returns.result import Success, Failure

>>> from returns.pointfree import bind\_context

>>> def function(arg: int) -> RequiresContext[str, int]:

...     return RequiresContext(lambda deps: len(deps) + arg)

>>> assert bind\_context(function)(

...     RequiresContextResult.from\_value(2),

... )('abc') == Success(5)

>>> assert bind\_context(function)(

...     RequiresContextResult.from\_failure(0),

... )('abc') == Failure(0)

```

Note, that this function works with only `Kind3` containers

with `.bind\_context` method.

See `returns.primitives.interfaces.specific.reader.ReaderLike3`

for more info.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_FirstType`)], [`RequiresContext`](index.html#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[`TypeVar`(`\_UpdatedType`), `TypeVar`(`\_ThirdType`)]]) – 

Return type:

[`Kinded`](index.html#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded")[`Callable`[[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_Reader3Kind`, bound= [`ReaderLike3`](index.html#returns.interfaces.specific.reader.ReaderLike3 "returns.interfaces.specific.reader.ReaderLike3")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_Reader3Kind`, bound= [`ReaderLike3`](index.html#returns.interfaces.specific.reader.ReaderLike3 "returns.interfaces.specific.reader.ReaderLike3")), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]]

bind\_context(*function*)[¶](#returns.pointfree.bind_context "Permalink to this definition")

Useful alias for [`bind\_context3()`](#returns.pointfree.bind_context3 "returns.pointfree.bind_context3").

Parameters:

**function** (`Callable`[[`TypeVar`(`\_FirstType`)], [`RequiresContext`](index.html#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext")[`TypeVar`(`\_UpdatedType`), `TypeVar`(`\_ThirdType`)]]) – 

Return type:

[`Kinded`](index.html#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded")[`Callable`[[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_Reader3Kind`, bound= [`ReaderLike3`](index.html#returns.interfaces.specific.reader.ReaderLike3 "returns.interfaces.specific.reader.ReaderLike3")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_Reader3Kind`, bound= [`ReaderLike3`](index.html#returns.interfaces.specific.reader.ReaderLike3 "returns.interfaces.specific.reader.ReaderLike3")), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]]

modify\_env2(*function*)[[source]](_modules/returns/pointfree/modify_env.html#modify_env2)[¶](#returns.pointfree.modify_env2 "Permalink to this definition")

Modifies the second type argument of a `ReaderLike2`.

In other words, it modifies the function’s

signature from:

`a -> b`

to:

`Container[x, a] -> Container[x, b]`

```

>>> from returns.pointfree import modify\_env2

>>> from returns.context import RequiresContext

>>> def multiply(arg: int) -> RequiresContext[int, int]:

...     return RequiresContext(lambda deps: arg \* deps)

>>> assert modify\_env2(int)(multiply(3))('4') == 12

```

Note, that this function works with only `Kind2` containers

with `.modify\_env` method.

See `returns.primitives.interfaces.specific.reader.ReaderLike2`

for more info.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_UpdatedType`)], `TypeVar`(`\_SecondType`)]) – 

Return type:

[`Kinded`](index.html#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded")[`Callable`[[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_Reader2Kind`, bound= [`ReaderLike2`](index.html#returns.interfaces.specific.reader.ReaderLike2 "returns.interfaces.specific.reader.ReaderLike2")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `Any`]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_Reader2Kind`, bound= [`ReaderLike2`](index.html#returns.interfaces.specific.reader.ReaderLike2 "returns.interfaces.specific.reader.ReaderLike2")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_UpdatedType`), `Any`]]]

modify\_env3(*function*)[[source]](_modules/returns/pointfree/modify_env.html#modify_env3)[¶](#returns.pointfree.modify_env3 "Permalink to this definition")

Modifies the third type argument of a `ReaderLike3`.

In other words, it modifies the function’s

signature from: `a -> b`

to: `Container[x, a] -> Container[x, b]`

```

>>> from returns.pointfree import modify\_env

>>> from returns.context import RequiresContextResultE

>>> from returns.result import Success, safe

>>> def divide(arg: int) -> RequiresContextResultE[float, int]:

...     return RequiresContextResultE(safe(lambda deps: arg / deps))

>>> assert modify\_env(int)(divide(3))('2') == Success(1.5)

>>> assert modify\_env(int)(divide(3))('0').failure()

```

Note, that this function works with only `Kind3` containers

with `.modify\_env` method.

See `returns.primitives.interfaces.specific.reader.ReaderLike3`

for more info.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_UpdatedType`)], `TypeVar`(`\_ThirdType`)]) – 

Return type:

[`Kinded`](index.html#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded")[`Callable`[[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_Reader3Kind`, bound= [`ReaderLike3`](index.html#returns.interfaces.specific.reader.ReaderLike3 "returns.interfaces.specific.reader.ReaderLike3")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_Reader3Kind`, bound= [`ReaderLike3`](index.html#returns.interfaces.specific.reader.ReaderLike3 "returns.interfaces.specific.reader.ReaderLike3")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_UpdatedType`)]]]

modify\_env(*function*)[¶](#returns.pointfree.modify_env "Permalink to this definition")

Useful alias for [`modify\_env3()`](#returns.pointfree.modify_env3 "returns.pointfree.modify_env3").

Parameters:

**function** (`Callable`[[`TypeVar`(`\_UpdatedType`)], `TypeVar`(`\_ThirdType`)]) – 

Return type:

[`Kinded`](index.html#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded")[`Callable`[[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_Reader3Kind`, bound= [`ReaderLike3`](index.html#returns.interfaces.specific.reader.ReaderLike3 "returns.interfaces.specific.reader.ReaderLike3")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_Reader3Kind`, bound= [`ReaderLike3`](index.html#returns.interfaces.specific.reader.ReaderLike3 "returns.interfaces.specific.reader.ReaderLike3")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_UpdatedType`)]]]

bind\_context\_result(*function*)[[source]](_modules/returns/pointfree/bind_context_result.html#bind_context_result)[¶](#returns.pointfree.bind_context_result "Permalink to this definition")

Composes successful container with a function that returns a container.

In other words, it modifies the function’s

signature from:

`a -> ReaderResult[b, c, e]`

to:

`Container[a, c, e] -> Container[b, c, e]`

```

>>> from returns.pointfree import bind\_context\_result

>>> from returns.context import ReaderIOResult, ReaderResult

>>> from returns.io import IOSuccess, IOFailure

>>> def example(argument: int) -> ReaderResult[int, str, str]:

...     return ReaderResult.from\_value(argument + 1)

>>> assert bind\_context\_result(example)(

...     ReaderIOResult.from\_value(1),

... )(...) == IOSuccess(2)

>>> assert bind\_context\_result(example)(

...     ReaderIOResult.from\_failure('a'),

... )(...) == IOFailure('a')

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_FirstType`)], [`RequiresContextResult`](index.html#returns.context.requires_context_result.RequiresContextResult "returns.context.requires_context_result.RequiresContextResult")[`TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]) – 

Return type:

[`Kinded`](index.html#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded")[`Callable`[[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ReaderResultLikeKind`, bound= [`ReaderResultLikeN`](index.html#returns.interfaces.specific.reader_result.ReaderResultLikeN "returns.interfaces.specific.reader_result.ReaderResultLikeN")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ReaderResultLikeKind`, bound= [`ReaderResultLikeN`](index.html#returns.interfaces.specific.reader_result.ReaderResultLikeN "returns.interfaces.specific.reader_result.ReaderResultLikeN")), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]]

bind\_context\_ioresult(*function*)[[source]](_modules/returns/pointfree/bind_context_ioresult.html#bind_context_ioresult)[¶](#returns.pointfree.bind_context_ioresult "Permalink to this definition")

Lifts function from `RequiresContextIOResult` for better composition.

In other words, it modifies the function’s

signature from:

`a -> RequiresContextIOResult[env, b, c]`

to:

`Container[env, a, c]` -> `Container[env, b, c]`

```

>>> import anyio

>>> from returns.context import (

...     RequiresContextFutureResult,

...     RequiresContextIOResult,

... )

>>> from returns.io import IOSuccess, IOFailure

>>> from returns.pointfree import bind\_context\_ioresult

>>> def function(arg: int) -> RequiresContextIOResult[str, int, str]:

...     return RequiresContextIOResult(

...         lambda deps: IOSuccess(len(deps) + arg),

...     )

>>> assert anyio.run(bind\_context\_ioresult(function)(

...     RequiresContextFutureResult.from\_value(2),

... )('abc').awaitable) == IOSuccess(5)

>>> assert anyio.run(bind\_context\_ioresult(function)(

...     RequiresContextFutureResult.from\_failure(0),

... )('abc').awaitable) == IOFailure(0)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_FirstType`)], [`RequiresContextIOResult`](index.html#returns.context.requires_context_ioresult.RequiresContextIOResult "returns.context.requires_context_ioresult.RequiresContextIOResult")[`TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]) – 

Return type:

[`Kinded`](index.html#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded")[`Callable`[[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ReaderIOResultLikeKind`, bound= [`ReaderIOResultLikeN`](index.html#returns.interfaces.specific.reader_ioresult.ReaderIOResultLikeN "returns.interfaces.specific.reader_ioresult.ReaderIOResultLikeN")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ReaderIOResultLikeKind`, bound= [`ReaderIOResultLikeN`](index.html#returns.interfaces.specific.reader_ioresult.ReaderIOResultLikeN "returns.interfaces.specific.reader_ioresult.ReaderIOResultLikeN")), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]]

bind\_async(*function*)[[source]](_modules/returns/pointfree/bind_async.html#bind_async)[¶](#returns.pointfree.bind_async "Permalink to this definition")

Compose a container and `async` function returning a container.

In other words, it modifies the function’s

signature from:

`a -> Awaitable[Container[b]]`

to:

`Container[a] -> Container[b]`

This is how it should be used:

```

>>> import anyio

>>> from returns.future import Future

>>> from returns.io import IO

>>> from returns.pointfree import bind\_async

>>> async def coroutine(x: int) -> Future[str]:

...    return Future.from\_value(str(x + 1))

>>> bound = bind\_async(coroutine)(Future.from\_value(1))

>>> assert anyio.run(bound.awaitable) == IO('2')

```

Note, that this function works

for all containers with `.bind\_async` method.

See `returns.primitives.interfaces.specific.future.FutureLikeN`

for more info.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_FirstType`)], `Awaitable`[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_FutureKind`, bound= [`FutureLikeN`](index.html#returns.interfaces.specific.future.FutureLikeN "returns.interfaces.specific.future.FutureLikeN")), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]]) – 

Return type:

[`Kinded`](index.html#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded")[`Callable`[[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_FutureKind`, bound= [`FutureLikeN`](index.html#returns.interfaces.specific.future.FutureLikeN "returns.interfaces.specific.future.FutureLikeN")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_FutureKind`, bound= [`FutureLikeN`](index.html#returns.interfaces.specific.future.FutureLikeN "returns.interfaces.specific.future.FutureLikeN")), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]]

bind\_awaitable(*function*)[[source]](_modules/returns/pointfree/bind_awaitable.html#bind_awaitable)[¶](#returns.pointfree.bind_awaitable "Permalink to this definition")

Composes a container a regular `async` function.

This function should return plain, non-container value.

In other words, it modifies the function’s

signature from:

`a -> Awaitable[b]`

to:

`Container[a] -> Container[b]`

This is how it should be used:

```

>>> import anyio

>>> from returns.future import Future

>>> from returns.io import IO

>>> from returns.pointfree import bind\_awaitable

>>> async def coroutine(x: int) -> int:

...    return x + 1

>>> assert anyio.run(

...     bind\_awaitable(coroutine)(Future.from\_value(1)).awaitable,

... ) == IO(2)

```

Note, that this function works

for all containers with `.bind\_awaitable` method.

See `returns.primitives.interfaces.specific.future.FutureLikeN`

for more info.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_FirstType`)], `Awaitable`[`TypeVar`(`\_UpdatedType`)]]) – 

Return type:

[`Kinded`](index.html#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded")[`Callable`[[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_FutureKind`, bound= [`FutureLikeN`](index.html#returns.interfaces.specific.future.FutureLikeN "returns.interfaces.specific.future.FutureLikeN")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_FutureKind`, bound= [`FutureLikeN`](index.html#returns.interfaces.specific.future.FutureLikeN "returns.interfaces.specific.future.FutureLikeN")), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]]

bind\_optional(*function*)[[source]](_modules/returns/pointfree/bind_optional.html#bind_optional)[¶](#returns.pointfree.bind_optional "Permalink to this definition")

Binds a function returning optional value over a container.

In other words, it modifies the function’s

signature from:

`a -> Optional[b]`

to:

`Container[a] -> Container[b]`

```

>>> from typing import Optional

>>> from returns.pointfree import bind\_optional

>>> from returns.maybe import Some, Nothing

>>> def example(argument: int) -> Optional[int]:

...     return argument + 1 if argument > 0 else None

>>> assert bind\_optional(example)(Some(1)) == Some(2)

>>> assert bind\_optional(example)(Some(0)) == Nothing

>>> assert bind\_optional(example)(Nothing) == Nothing

```

Note, that this function works

for all containers with `.bind\_optional` method.

See `returns.primitives.interfaces.specific.maybe.\_MaybeLikeKind`

for more info.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_FirstType`)], `Optional`[`TypeVar`(`\_UpdatedType`)]]) – 

Return type:

[`Kinded`](index.html#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded")[`Callable`[[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_MaybeLikeKind`, bound= [`MaybeLikeN`](index.html#returns.interfaces.specific.maybe.MaybeLikeN "returns.interfaces.specific.maybe.MaybeLikeN")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_MaybeLikeKind`, bound= [`MaybeLikeN`](index.html#returns.interfaces.specific.maybe.MaybeLikeN "returns.interfaces.specific.maybe.MaybeLikeN")), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]]

compose\_result(*function*)[[source]](_modules/returns/pointfree/compose_result.html#compose_result)[¶](#returns.pointfree.compose_result "Permalink to this definition")

Composes inner `Result` with `IOResultLike` returning function.

Can be useful when you need an access to both states of the result.

```

>>> from returns.io import IOResult, IOSuccess, IOFailure

>>> from returns.pointfree import compose\_result

>>> from returns.result import Result

>>> def modify\_string(container: Result[str, str]) -> IOResult[str, str]:

...     return IOResult.from\_result(

...         container.map(str.upper).alt(str.lower),

...     )

>>> assert compose\_result(modify\_string)(

...     IOSuccess('success')

... ) == IOSuccess('SUCCESS')

>>> assert compose\_result(modify\_string)(

...     IOFailure('FAILURE')

... ) == IOFailure('failure')

```

Parameters:

**function** (`Callable`[[[`Result`](index.html#returns.result.Result "returns.result.Result")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_IOResultLikeKind`, bound= [`IOResultLikeN`](index.html#returns.interfaces.specific.ioresult.IOResultLikeN "returns.interfaces.specific.ioresult.IOResultLikeN")), `TypeVar`(`\_NewFirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]) – 

Return type:

[`Kinded`](index.html#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded")[`Callable`[[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_IOResultLikeKind`, bound= [`IOResultLikeN`](index.html#returns.interfaces.specific.ioresult.IOResultLikeN "returns.interfaces.specific.ioresult.IOResultLikeN")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_IOResultLikeKind`, bound= [`IOResultLikeN`](index.html#returns.interfaces.specific.ioresult.IOResultLikeN "returns.interfaces.specific.ioresult.IOResultLikeN")), `TypeVar`(`\_NewFirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]]

cond(*container\_type*, *success\_value*, *error\_value=None*)[[source]](_modules/returns/pointfree/cond.html#cond)[¶](#returns.pointfree.cond "Permalink to this definition")

Reduce the boilerplate when choosing paths.

Works with `SingleFailableN` (e.g. `Maybe`)

and `DiverseFailableN` (e.g. `Result`).

Example using `cond` with the `Result` container:

```

>>> from returns.pointfree import cond

>>> from returns.result import Failure, Result, Success

>>> assert cond(Result, 'success', 'failure')(True) == Success('success')

>>> assert cond(Result, 'success', 'failure')(False) == Failure('failure')

```

Example using `cond` with the `Maybe` container:

```

>>> from returns.maybe import Maybe, Some, Nothing

>>> assert cond(Maybe, 10.0)(True) == Some(10.0)

>>> assert cond(Maybe, 10.0)(False) == Nothing

```

Parameters:

* **container\_type** (`Union`[`Type`[`TypeVar`(`\_SingleFailableKind`, bound= [`SingleFailableN`](index.html#returns.interfaces.failable.SingleFailableN "returns.interfaces.failable.SingleFailableN"))], `Type`[`TypeVar`(`\_DiverseFailableKind`, bound= [`DiverseFailableN`](index.html#returns.interfaces.failable.DiverseFailableN "returns.interfaces.failable.DiverseFailableN"))]]) –

* **success\_value** (`TypeVar`(`\_ValueType`)) –

* **error\_value** (`Optional`[`TypeVar`(`\_ErrorType`)]) –

alt(*function*)[[source]](_modules/returns/pointfree/alt.html#alt)[¶](#returns.pointfree.alt "Permalink to this definition")

Lifts function to be wrapped in a container for better composition.

In other words, it modifies the function’s

signature from:

`a -> b`

to:

`Container[a] -> Container[b]`

This is how it should be used:

```

>>> from returns.io import IOFailure, IOSuccess

>>> from returns.pointfree import alt

>>> def example(argument: int) -> float:

...     return argument / 2

>>> assert alt(example)(IOSuccess(1)) == IOSuccess(1)

>>> assert alt(example)(IOFailure(4)) == IOFailure(2.0)

```

Note, that this function works for all containers with `.alt` method.

See `returns.primitives.interfaces.altable.AltableN` for more info.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_SecondType`)], `TypeVar`(`\_UpdatedType`)]) – 

Return type:

[`Kinded`](index.html#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded")[`Callable`[[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_AltableKind`, bound= [`AltableN`](index.html#returns.interfaces.altable.AltableN "returns.interfaces.altable.AltableN")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_AltableKind`, bound= [`AltableN`](index.html#returns.interfaces.altable.AltableN "returns.interfaces.altable.AltableN")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_ThirdType`)]]]

lash(*function*)[[source]](_modules/returns/pointfree/lash.html#lash)[¶](#returns.pointfree.lash "Permalink to this definition")

Turns function’s input parameter from a regular value to a container.

In other words, it modifies the function

signature from:

`a -> Container[b]`

to:

`Container[a] -> Container[b]`

Similar to [`returns.pointfree.bind()`](#returns.pointfree.bind "returns.pointfree.bind"), but works for failed containers.

This is how it should be used:

```

>>> from returns.pointfree import lash

>>> from returns.result import Success, Failure, Result

>>> def example(argument: int) -> Result[str, int]:

...     return Success(argument + 1)

>>> assert lash(example)(Success('a')) == Success('a')

>>> assert lash(example)(Failure(1)) == Success(2)

```

Note, that this function works for all containers with `.lash` method.

See `returns.interfaces.lashable.Lashable` for more info.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_SecondType`)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_LashableKind`, bound= [`LashableN`](index.html#returns.interfaces.lashable.LashableN "returns.interfaces.lashable.LashableN")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_ThirdType`)]]) – 

Return type:

[`Kinded`](index.html#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded")[`Callable`[[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_LashableKind`, bound= [`LashableN`](index.html#returns.interfaces.lashable.LashableN "returns.interfaces.lashable.LashableN")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_LashableKind`, bound= [`LashableN`](index.html#returns.interfaces.lashable.LashableN "returns.interfaces.lashable.LashableN")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_ThirdType`)]]]

unify(*function*)[[source]](_modules/returns/pointfree/unify.html#unify)[¶](#returns.pointfree.unify "Permalink to this definition")

Composes successful container with a function that returns a container.

Similar to [`bind()`](#returns.pointfree.bind "returns.pointfree.bind") but has different type.

It returns `Result[ValueType, Union[OldErrorType, NewErrorType]]`

instead of `Result[ValueType, OldErrorType]`.

So, it can be more useful in some situations.

Probably with specific exceptions.

```

>>> from returns.methods import cond

>>> from returns.pointfree import unify

>>> from returns.result import Result, Success, Failure

>>> def bindable(arg: int) -> Result[int, int]:

...     return cond(Result, arg % 2 == 0, arg + 1, arg - 1)

>>> assert unify(bindable)(Success(2)) == Success(3)

>>> assert unify(bindable)(Success(1)) == Failure(0)

>>> assert unify(bindable)(Failure(42)) == Failure(42)

```

Parameters:

**function** (`Callable`[[`TypeVar`(`\_FirstType`)], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_DiverseFailableKind`, bound= [`DiverseFailableN`](index.html#returns.interfaces.failable.DiverseFailableN "returns.interfaces.failable.DiverseFailableN")), `TypeVar`(`\_NewFirstType`), `TypeVar`(`\_NewSecondType`), `TypeVar`(`\_NewThirdType`)]]) – 

Return type:

[`Kinded`](index.html#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded")[`Callable`[[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_DiverseFailableKind`, bound= [`DiverseFailableN`](index.html#returns.interfaces.failable.DiverseFailableN "returns.interfaces.failable.DiverseFailableN")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_DiverseFailableKind`, bound= [`DiverseFailableN`](index.html#returns.interfaces.failable.DiverseFailableN "returns.interfaces.failable.DiverseFailableN")), `TypeVar`(`\_NewFirstType`), `Union`[`TypeVar`(`\_SecondType`), `TypeVar`(`\_NewSecondType`)], `TypeVar`(`\_NewThirdType`)]]]

apply(*container*)[[source]](_modules/returns/pointfree/apply.html#apply)[¶](#returns.pointfree.apply "Permalink to this definition")

Turns container containing a function into a callable.

In other words, it modifies the function

signature from:

`Container[a -> b]`

to:

`Container[a] -> Container[b]`

This is how it should be used:

```

>>> from returns.pointfree import apply

>>> from returns.maybe import Some, Nothing

>>> def example(argument: int) -> int:

...     return argument + 1

>>> assert apply(Some(example))(Some(1)) == Some(2)

>>> assert apply(Some(example))(Nothing) == Nothing

>>> assert apply(Nothing)(Some(1)) == Nothing

>>> assert apply(Nothing)(Nothing) == Nothing

```

Note, that this function works for all containers with `.apply` method.

See [`returns.interfaces.applicative.ApplicativeN`](index.html#returns.interfaces.applicative.ApplicativeN "returns.interfaces.applicative.ApplicativeN") for more info.

Parameters:

**container** ([`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ApplicativeKind`, bound= [`ApplicativeN`](index.html#returns.interfaces.applicative.ApplicativeN "returns.interfaces.applicative.ApplicativeN")), `Callable`[[`TypeVar`(`\_FirstType`)], `TypeVar`(`\_UpdatedType`)], `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) – 

Return type:

[`Kinded`](index.html#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded")[`Callable`[[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ApplicativeKind`, bound= [`ApplicativeN`](index.html#returns.interfaces.applicative.ApplicativeN "returns.interfaces.applicative.ApplicativeN")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]], [`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ApplicativeKind`, bound= [`ApplicativeN`](index.html#returns.interfaces.applicative.ApplicativeN "returns.interfaces.applicative.ApplicativeN")), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]]

Methods[¶](#methods "Permalink to this heading")

------------------------------------------------

The following useful methods can be used to interact with interfaces.

### cond[¶](#cond "Permalink to this heading")

Reduce the boilerplate when choosing paths with `DiverseFailableN`.

Think of this method as a functional `if` alternative

for successful or failed types.

So, this code:

```

>>> from returns.result import Failure, Result, Success

>>> def is\_numeric(string: str) -> Result[str, str]:

...     if string.isnumeric():

...          return Success('It is a number')

...     return Failure('It is not a number')

```

Can be replaced with this:

```

>>> from returns.methods import cond

>>> from returns.result import Failure, Result, Success

>>> def is\_numeric(string: str) -> Result[str, str]:

...     return cond(

...         Result,

...         string.isnumeric(),

...         'It is a number',

...         'It is not a number',

...    )

>>> assert is\_numeric('42') == Success('It is a number')

>>> assert is\_numeric('text') == Failure('It is not a number')

```

Why is it helpful? Because `cond` can be easily added

into a [Pipelines](index.html#pipelines) of functions.

### unwrap\_or\_failure[¶](#unwrap-or-failure "Permalink to this heading")

Unwraps either a successful or failed value.

```

>>> from returns.io import IO, IOSuccess, IOFailure

>>> from returns.methods import unwrap\_or\_failure

>>> assert unwrap\_or\_failure(IOSuccess(1)) == IO(1)

>>> assert unwrap\_or\_failure(IOFailure('a')) == IO('a')

```

Useful when you have a `ResultLike` value with correctly handled error value,

for example with `bimap()`.

Here’s a full example:

```

>>> from returns.result import Failure, Result, Success

>>> from returns.methods import unwrap\_or\_failure

>>> from returns.pointfree import bimap

>>> instance: Result[int, str] = Success(1)

>>> error\_handled = bimap(lambda inr: inr + 1, lambda \_: 0)(instance)

>>> assert isinstance(unwrap\_or\_failure(error\_handled), int)

```

### API Reference[¶](#api-reference "Permalink to this heading")

cond(*container\_type*, *is\_success*, *success\_value*, *error\_value=None*)[¶](#returns.methods.cond "Permalink to this definition")

Kinded version of `internal\_cond()`, use it to infer real return type.

Parameters:

* **container\_type** (`Union`[`Type`[`TypeVar`(`\_SingleFailableKind`, bound= [`SingleFailableN`](index.html#returns.interfaces.failable.SingleFailableN "returns.interfaces.failable.SingleFailableN"))], `Type`[`TypeVar`(`\_DiverseFailableKind`, bound= [`DiverseFailableN`](index.html#returns.interfaces.failable.DiverseFailableN "returns.interfaces.failable.DiverseFailableN"))]]) –

* **is\_success** (`bool`) –

* **success\_value** (`TypeVar`(`\_ValueType`)) –

* **error\_value** (`Optional`[`TypeVar`(`\_ErrorType`)]) –

unwrap\_or\_failure(*container*)[[source]](_modules/returns/methods/unwrap_or_failure.html#unwrap_or_failure)[¶](#returns.methods.unwrap_or_failure "Permalink to this definition")

Unwraps either successful or failed value.

```

>>> from returns.io import IO, IOSuccess, IOFailure

>>> from returns.methods import unwrap\_or\_failure

>>> assert unwrap\_or\_failure(IOSuccess(1)) == IO(1)

>>> assert unwrap\_or\_failure(IOFailure('a')) == IO('a')

```

Parameters:

**container** ([`Unwrappable`](index.html#returns.interfaces.unwrappable.Unwrappable "returns.interfaces.unwrappable.Unwrappable")[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`)]) – 

Return type:

`Union`[`TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`)]

Do Notation[¶](#do-notation "Permalink to this heading")

--------------------------------------------------------

Note

Technical note: this feature requires [mypy plugin](index.html#mypy-plugins).

All containers can be easily composed

with functions that can take a single argument.

But, what if we need to compose two containers

with a function with two arguments?

That’s not so easy.

Of course, we can use [Curry](index.html#curry) and `.apply` or some imperative code.

But, it is not very easy to write and read.

This is why multiple functional languages have a concept of “do-notation”.

It allows you to write beautiful imperative code.

### Regular containers[¶](#regular-containers "Permalink to this heading")

Let’s say we have a function called `add` which is defined like this:

```

>>> def add(one: int, two: int) -> int:

...     return one + two

```

And we have two containers: `IO(2)` and `IO(3)`.

How can we easily get `IO(5)` in this case?

Luckily, `IO` defines [`returns.io.IO.do()`](index.html#returns.io.IO.do "returns.io.IO.do") which can help us:

```

>>> from returns.io import IO

>>> assert IO.do(

...     add(first, second)

...     for first in IO(2)

...     for second in IO(3)

... ) == IO(5)

```

Notice, that you don’t have two write any complicated code.

Everything is pythonic and readable.

However, we still need to explain what `for` does here.

It uses Python’s `\_\_iter\_\_` method which returns an iterable

with strictly a single raw value inside.

Warning

Please, don’t use `for x in container` outside of do-notation.

It does not make much sense.

Basically, for `IO(2)` it will return just `2`.

Then, `IO.do` wraps it into `IO` once again.

#### Errors[¶](#errors "Permalink to this heading")

Containers like `Result` and `IOResult` can sometimes represent errors.

In this case, do-notation expression will return the first found error.

For example:

```

>>> from returns.result import Success, Failure, Result

>>> assert Result.do(

...     first + second

...     for first in Failure('a')

...     for second in Success(3)

... ) == Failure('a')

```

This behavior is consistent with `.map` and other methods.

### Async containers[¶](#async-containers "Permalink to this heading")

We also support async containers like `Future` and `FutureResult`.

It works in a similar way as regular sync containers.

But, they require `async for` expressions instead of regular `for` ones.

And because of that - they cannot be used outsided of `async def` context.

Usage example:

```

>>> import anyio

>>> from returns.future import Future

>>> from returns.io import IO

>>> async def main() -> None:

...     return await Future.do(

...         first + second

...         async for first in Future.from\_value(1)

...         async for second in Future.from\_value(2)

...     )

>>> assert anyio.run(main) == IO(3)

```

### FAQ[¶](#faq "Permalink to this heading")

#### Why don’t we allow mixing different container types?[¶](#why-don-t-we-allow-mixing-different-container-types "Permalink to this heading")

One might ask, why don’t we allow mixing multiple container types

in a single do-notation expression?

For example, this code will not what you expect:

```

>>> from returns.result import Result, Success

>>> from returns.io import IOResult, IOSuccess

>>> assert Result.do(

...     first + second

...     for first in Success(2)

...     for second in IOSuccess(3)  # Notice the IO part here

... ) == Success(5)

```

This code will raise a mypy error at `for second in IOSuccess(3)` part:

```

Invalid type supplied in do-notation: expected "returns.result.Result[Any, Any]", got "returns.io.IOSuccess[builtins.int\*]"

```

Notice, that the `IO` part is gone in the final result. This is not right.

And we can’t track this in any manner.

So, we require all containers to have the same type.

The code above must be rewritten as:

```

>>> from returns.result import Success

>>> from returns.io import IOResult, IOSuccess

>>> assert IOResult.do(

...     first + second

...     for first in IOResult.from\_result(Success(2))

...     for second in IOSuccess(3)

... ) == IOSuccess(5)

```

Now, it is correct. `IO` part is safe, the final result is correct.

And mypy is happy.

#### Why don’t we allow `if` conditions in generator expressions?[¶](#why-don-t-we-allow-if-conditions-in-generator-expressions "Permalink to this heading")

At the moment, using `if` conditions inside generator expressions

passed into `.do` method is not allowed. Why?

Because if the `if` condition will return `False`,

we will have an empty iterable and `StopIteration` will be thrown.

```

>>> from returns.io import IO

>>> IO.do(

...     first + second

...     for first in IO(2)

...     for second in IO(3)

...     if second > 10

... )

Traceback (most recent call last):

 ...

StopIteration

```

It will raise:

```

Using "if" conditions inside a generator is not allowed

```

Instead, use conditions and checks inside your logic, not inside your generator.

#### Why do we require a literal expression in do-notation?[¶](#why-do-we-require-a-literal-expression-in-do-notation "Permalink to this heading")

This code will work in runtime, but will raise a mypy error:

```

>>> from returns.result import Result, Success

>>> expr = (

...     first + second

...     for first in Success(2)

...     for second in Success(3)

... )

>>>

>>> assert Result.do(expr) == Success(5)

```

It raises:

```

Literal generator expression is required, not a variable or function call

```

This happens, because of mypy’s plugin API.

We need the whole expression to make sure it is correct.

We cannot use variables and function calls in its place.

### Further reading[¶](#further-reading "Permalink to this heading")

* [Do notation in Haskell](https://en.wikibooks.org/wiki/Haskell/do_notation)

Helper functions[¶](#helper-functions "Permalink to this heading")

------------------------------------------------------------------

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

### compose[¶](#compose "Permalink to this heading")

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

```

>>> from returns.functions import compose

>>> bool\_after\_int = compose(int, bool)

>>> assert bool\_after\_int('1') is True

>>> assert bool\_after\_int('0') is 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).

Warning

`compose` might fail to infer types for some functions.

There are several problems: `lambda` and generic functions.

In these cases `mypy` will fail to infer

the types of the resulting function.

In this case, use `pipe`

it does the same thing, but has pretty good type inference.

Or use manual annotations with `Callable` type.

### identity[¶](#identity "Permalink to this heading")

We also ship [`returns.functions.identity()`](#returns.functions.identity "returns.functions.identity") function

to help you with the composition.

Identity function is a simple concept: it just returns its argument.

If you wonder why do we need this function, please read below:

* [Practical Usage of Identity Function](https://blog.bigbinary.com/2018/03/20/practical-usage-of-identity-function.html) (JS)

* [Using Identity Functions](https://emilvarga.com/posts/2016/08/01/using-identity-functions) (Scala)

### tap and untap[¶](#tap-and-untap "Permalink to this heading")

We need `tap()` function to easily compose values

with functions that does not return.

For example you sometimes need to `print()` values inside your [pipe](index.html#pipe):

```

>>> from returns.functions import tap

>>> result = tap(print)(1)  # will print and return 1

1

>>> assert result == 1

```

You can also use the `untap` function to turn any function’s

return type to `None` and still do its thing:

```

>>> from returns.functions import tap, untap

>>> result = untap(tap(print))(1)  # will print and return None

1

>>> assert result is None

```

This is also sometimes helpful for a typed function composition.

### raise\_exception[¶](#raise-exception "Permalink to this heading")

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

def create\_account\_and\_user(username: str) -> ...:

 """

 Creates new Account-User pair.

 Imagine, that you need to reraise ValidationErrors due to existing API.

 """

    return \_validate\_user(

        username,

    ).alt(

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

        raise\_exception,

    )

def \_validate\_user(username: str) -> Result['User', ValidationError]:

    ...

```

Use this with caution. We try to remove exceptions from our code base.

Original proposal is [here](https://github.com/dry-python/returns/issues/56).

### not\_[¶](#not "Permalink to this heading")

With `not\_` helper function we can easily deny a function returns.

It supports functions with one or more arguments.

```

>>> from typing import List

>>> from returns.functions import compose, not\_

>>> def is\_even(number: int) -> bool:

...     return number % 2 == 0

>>> def number\_is\_in\_list(number: int, list\_: List[int]) -> bool:

...     return number in list\_

>>> assert not\_(is\_even)(2) is False

>>> assert not\_(number\_is\_in\_list)(1, [2, 3, 4]) is True

>>> assert compose(int, not\_(is\_even))("1") is True

```

### API Reference[¶](#module-returns.functions "Permalink to this heading")

identity(*instance*)[[source]](_modules/returns/functions.html#identity)[¶](#returns.functions.identity "Permalink to this definition")

Function that returns its argument.

```

>>> assert identity(1) == 1

>>> assert identity([1, 2, 3]) == [1, 2, 3]

```

This function is really helpful for some composition.

It is also useful for “do nothing” use-case.

See also

* <https://en.wikipedia.org/wiki/Identity_function>

* <https://stackoverflow.com/a/21506571/4842742>

Parameters:

**instance** (`TypeVar`(`\_FirstType`)) – 

Return type:

`TypeVar`(`\_FirstType`)

compose(*first*, *second*)[[source]](_modules/returns/functions.html#compose)[¶](#returns.functions.compose "Permalink to this definition")

Allows function composition.

Works as: `second . first` or `first() |> second()`.

You can read it as “second after first”.

```

>>> assert compose(float, int)('123.5') == 123

```

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

Type checked.

Parameters:

* **first** (`Callable`[[`TypeVar`(`\_FirstType`)], `TypeVar`(`\_SecondType`)]) –

* **second** (`Callable`[[`TypeVar`(`\_SecondType`)], `TypeVar`(`\_ThirdType`)]) –

Return type:

`Callable`[[`TypeVar`(`\_FirstType`)], `TypeVar`(`\_ThirdType`)]

tap(*function*)[[source]](_modules/returns/functions.html#tap)[¶](#returns.functions.tap "Permalink to this definition")

Allows to apply some function and return an argument, instead of a result.

Is useful for composing functions with

side-effects like `print()`, `logger.log()`, etc.

```

>>> assert tap(print)(1) == 1

1

>>> assert tap(lambda \_: 1)(2) == 2

```

See also

* <https://github.com/dry-python/returns/issues/145>

Parameters:

**function** (`Callable`[[`TypeVar`(`\_FirstType`)], `Any`]) – 

Return type:

`Callable`[[`TypeVar`(`\_FirstType`)], `TypeVar`(`\_FirstType`)]

untap(*function*)[[source]](_modules/returns/functions.html#untap)[¶](#returns.functions.untap "Permalink to this definition")

Allows to apply some function and always return `None` as a result.

Is useful for composing functions that do some side effects

and return some nosense.

Is the kind of a reverse of the `tap` function.

```

>>> def strange\_log(arg: int) -> int:

...     print(arg)

...     return arg

>>> assert untap(strange\_log)(2) is None

2

>>> assert untap(tap(lambda \_: 1))(2) is None

```

See also

* <https://github.com/dry-python/returns/issues/145>

Parameters:

**function** (`Callable`[[`TypeVar`(`\_FirstType`)], `Any`]) – 

Return type:

`Callable`[[`TypeVar`(`\_FirstType`)], `None`]

raise\_exception(*exception*)[[source]](_modules/returns/functions.html#raise_exception)[¶](#returns.functions.raise_exception "Permalink to this definition")

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.result import Failure, Result

>>> # Some operation result:

>>> user: Result[int, ValueError] = Failure(ValueError('boom'))

>>> # Here we unwrap internal exception and raise it:

>>> user.alt(raise\_exception)

Traceback (most recent call last):

 ...

ValueError: boom

```

See also

* <https://github.com/dry-python/returns/issues/56>

Parameters:

**exception** (`Exception`) – 

Return type:

`NoReturn`

not\_(*function*)[[source]](_modules/returns/functions.html#not_)[¶](#returns.functions.not_ "Permalink to this definition")

Denies the function returns.

```

>>> from returns.result import Result, Success, Failure

>>> def is\_successful(result\_container: Result[float, int]) -> bool:

...     return isinstance(result\_container, Result.success\_type)

>>> assert not\_(is\_successful)(Success(1.0)) is False

>>> assert not\_(is\_successful)(Failure(1)) is True

```

Parameters:

**function** (`Callable`[[`ParamSpec`(`\_FuncParams`)], `bool`]) – 

Return type:

`Callable`[[`ParamSpec`(`\_FuncParams`)], `bool`]

Curry[¶](#curry "Permalink to this heading")

--------------------------------------------

This module is dedicated to partial application.

We support two types of partial application: `@curry` and `partial`.

`@curry` is a new concept for most Python developers,

but Python already has a great tool to use partial application:

[functools.partial](https://docs.python.org/3/library/functools.html#functools.partial)

The only problem with it is the lack of typing.

Let’s see what problems do we solve with this module.

Warning

This module requires [our mypy plugin](index.html#mypy-plugins) to be present.

Without it we will fallback to the original behaviour.

### Partial[¶](#partial "Permalink to this heading")

Here’s how typing works there:

```

from functools import partial

def some\_function(first: int, second: int) -> float:

    return first / second

reveal\_type(partial(some\_function, 1))

# => functools.partial[builtins.float\*]

# => Which is really: `def (\*Any, \*\*Any) -> builtins.float`

```

And compare it with our solution:

```

from returns.curry import partial

def some\_function(first: int, second: int) -> float:

    return first / second

reveal\_type(partial(some\_function, 1))

# => def (second: builtins.int) -> builtins.float\*

# => Which is fair!

```

Note

We still use `functools.partial` inside.

We just improve the typings.

#### Generics[¶](#generics "Permalink to this heading")

One more problem is generics support in `functools.partial`.

Here’s the comparison:

```

from functools import partial

from typing import List, TypeVar

T = TypeVar('T')

x: List[int]

def some\_function(first: List[T], second: int) -> T:

    return first[second]

reveal\_type(partial(some\_function, x))

# => functools.partial[T`-1]

# => Which is broken!

```

And our solution works fine:

```

from returns.curry import partial

reveal\_type(partial(some\_function, x))

# => def (second: builtins.int) -> builtins.int\*

```

We also work with complex generic

with multiple arguments or with multiple generics.

The only known problem is that passing explicit generic like `[1, 2, 3]`

will resolve in `List[Any]`. Because `mypy` won’t be able to infer

this type for some reason.

The reasonable work-around is to pass annotated

variables like in the example above.

#### Types and Instances[¶](#types-and-instances "Permalink to this heading")

We can also work with types and instances. Because they are callable too!

```

from returns.curry import partial

class Test(object):

    def \_\_init\_\_(self, arg: int) -> None:

        self.arg = arg

    def \_\_call\_\_(self, other: int) -> int:

        return self.arg + other

reveal\_type(partial(Test, 1))  # N: Revealed type is 'def () -> ex.Test'

reveal\_type(partial(Test(1), 1))  # N: Revealed type is 'def () -> builtins.int'

```

No differences with regular callables at all.

#### Overloads[¶](#overloads "Permalink to this heading")

We also support working with `@overload` definitions.

It also looks the same way:

```

from typing import overload

from returns.curry import partial

@overload

def test(a: int, b: str) -> str:

    ...

@overload

def test(a: int) -> int:

    ...

@overload

def test(a: str) -> None:  # won't match!

    ...

def test(a, b=None):

    ...

reveal\_type(partial(test, 1))  # N: Revealed type is 'Overload(def (b: builtins.str) -> builtins.str, def () -> builtins.int)'

```

From this return type you can see that we work

with all matching cases and discriminate unmatching ones.

### @curry[¶](#id3 "Permalink to this heading")

`curry` allows to provide only a subset of arguments to a function.

And it won’t be called until all the required arguments are provided.

In contrast to `partial` which works on the calling stage,

`@curry` works best when defining a new function.

```

>>> from returns.curry import curry

>>> @curry

... def function(first: int, second: str) -> bool:

...     return len(second) > first

>>> assert function(1)('a') is False

>>> assert function(1, 'a') is False

>>> assert function(2)('abc') is True

>>> assert function(2, 'abc') is True

```

Take a note, that providing invalid arguments will raise `TypeError`:

```

>>> function(1, 2, 3)

Traceback (most recent call last):

 ...

TypeError: too many positional arguments

>>> function(a=1)

Traceback (most recent call last):

 ...

TypeError: got an unexpected keyword argument 'a'

```

This is really helpful when working with `.apply()` method of containers.

Warning

We recommend using [partial](#partial) instead of `@curry` when

possible because it’s much faster.

#### Typing[¶](#typing "Permalink to this heading")

`@curry` functions are also fully typed with our custom `mypy` plugin.

Let’s see how types do look like for a curried function:

```

>>> from returns.curry import curry

>>> @curry

... def zero(a: int, b: float, \*, kw: bool) -> str:

...     return str(a - b) if kw else ''

>>> assert zero(1)(0.3)(kw=True) == '0.7'

>>> assert zero(1)(0.3, kw=False) == ''

# If we will reveal the type it would be quite big:

reveal\_type(zero)

# Overload(

# def (a: builtins.int) -> Overload(

# def (b: builtins.float, \*, kw: builtins.bool) -> builtins.str,

# def (b: builtins.float) -> def (\*, kw: builtins.bool) -> builtins.str

# ),

# def (a: builtins.int, b: builtins.float) -> def (\*, kw: builtins.bool)

# -> builtins.str,

# def (a: builtins.int, b: builtins.float, \*, kw: builtins.bool)

# -> builtins.str

# )

```

It reveals to us that there are 4 possible way to call this function.

And we type all of them with

[overload](https://mypy.readthedocs.io/en/stable/more_types.html#function-overloading)

type.

When you provide any arguments,

you discriminate some overloads and choose more specific path:

```

reveal\_type(zero(1, 2.0))

# By providing this set of arguments we have chosen this path:

#

# def (a: builtins.int, b: builtins.float) -> def (\*, kw: builtins.bool)

# -> builtins.str,

#

# And the revealed type would be:

#

# def (\*, kw: builtins.bool) -> builtins.str

#

```

It works with functions, instance, class,

and static methods, including generics.

See `Limitations` in the API Reference.

### FAQ[¶](#faq "Permalink to this heading")

#### Why don’t you support \* and \*\* arguments?[¶](#why-don-t-you-support-and-arguments "Permalink to this heading")

When you use `partial(some, \*my\_args)` or `partial(some, \*\*my\_args)`

or both of them at the same time,

we fallback to the default return type. The same happens with `curry`. Why?

There are several problems:

* Because `mypy` cannot not infer what arguments are there

inside this `my\_args` variable

* Because `curry` cannot know when

to stop accepting `\*args` and `\*\*kwargs`

* And there are possibly other problems!

Our advice is not to use `\*args` and `\*kwargs`

with `partial` and `curry`.

But, it is still possible, but in this case we will fallback to `Any`.

### Further reading[¶](#further-reading "Permalink to this heading")

* [functools.partial](https://docs.python.org/3/library/functools.html#functools.partial)

* [Currying](https://en.wikipedia.org/wiki/Currying)

* [@curry decorator](https://stackoverflow.com/questions/9458271/currying-decorator-in-python)

### API Reference[¶](#module-returns.curry "Permalink to this heading")

partial(*func*, *\*args*, *\*\*kwargs*)[[source]](_modules/returns/curry.html#partial)[¶](#returns.curry.partial "Permalink to this definition")

Typed partial application.

It is just a `functools.partial` wrapper with better typing support.

We use a custom `mypy` plugin to make sure types are correct.

Otherwise, it is currently impossible to properly type this function.

```

>>> from returns.curry import partial

>>> def sum\_two\_numbers(first: int, second: int) -> int:

...     return first + second

>>> sum\_with\_ten = partial(sum\_two\_numbers, 10)

>>> assert sum\_with\_ten(2) == 12

>>> assert sum\_with\_ten(-5) == 5

```

See also

* <https://docs.python.org/3/library/functools.html#functools.partial>

Parameters:

* **func** (`Callable`[`...`, `TypeVar`(`\_ReturnType`)]) –

* **args** (`Any`) –

* **kwargs** (`Any`) –

Return type:

`Callable`[`...`, `TypeVar`(`\_ReturnType`)]

curry(*function*)[[source]](_modules/returns/curry.html#curry)[¶](#returns.curry.curry "Permalink to this definition")

Typed currying decorator.

Currying is a conception from functional languages that does partial

applying. That means that if we pass one argument in a function that

gets 2 or more arguments, we’ll get a new function that remembers all

previously passed arguments. Then we can pass remaining arguments, and

the function will be executed.

[`partial()`](#returns.curry.partial "returns.curry.partial") function does a similar thing,

but it does partial application exactly once.

`curry` is a bit smarter and will do partial

application until enough arguments passed.

If wrong arguments are passed, `TypeError` will be raised immediately.

We use a custom `mypy` plugin to make sure types are correct.

Otherwise, it is currently impossible to properly type this function.

```

>>> from returns.curry import curry

>>> @curry

... def divide(number: int, by: int) -> float:

...     return number / by

>>> divide(1)  # doesn't call the func and remembers arguments

<function divide at ...>

>>> assert divide(1)(by=10) == 0.1  # calls the func when possible

>>> assert divide(1)(10) == 0.1  # calls the func when possible

>>> assert divide(1, by=10) == 0.1  # or call the func like always

```

Here are several examples with wrong arguments:

```

>>> divide(1, 2, 3)

Traceback (most recent call last):

 ...

TypeError: too many positional arguments

>>> divide(a=1)

Traceback (most recent call last):

 ...

TypeError: got an unexpected keyword argument 'a'

```

Limitations:

* It is kinda slow. Like 100 times slower than a regular function call.

* It does not work with several builtins like `str`, `int`,

and possibly other `C` defined callables

* `\*args` and `\*\*kwargs` are not supported

and we use `Any` as a fallback

* Support of arguments with default values is very limited,

because we cannot be totally sure which case we are using:

with the default value or without it, be careful

* We use a custom `mypy` plugin to make types correct,

otherwise, it is currently impossible

* It might not work as expected with curried `Klass().method`,

it might generate invalid method signature

(looks like a bug in `mypy`)

* It is probably a bad idea to `curry` a function with lots of arguments,

because you will end up with lots of overload functions,

that you won’t be able to understand.

It might also be slow during the typecheck

* Currying of `\_\_init\_\_` does not work because of the bug in `mypy`:

<https://github.com/python/mypy/issues/8801>

We expect people to use this tool responsibly

when they know that they are doing.

See also

* <https://en.wikipedia.org/wiki/Currying>

* <https://stackoverflow.com/questions/218025/>

Parameters:

**function** (`Callable`[`...`, `TypeVar`(`\_ReturnType`)]) – 

Return type:

`Callable`[`...`, `TypeVar`(`\_ReturnType`)]

Trampolines[¶](#trampolines "Permalink to this heading")

--------------------------------------------------------

Python does not support TCO (tail call optimization), so any recursion-based

algorithms become dangerous.

We cannot be sure that

they won’t cause `RecursionError` on deeply nested data.

Here’s why we need trampolines: they allow to replicate tail call optimization

by wrapping function calls into [`returns.trampolines.Trampoline`](#returns.trampolines.Trampoline "returns.trampolines.Trampoline") objects,

making recursion-based function *always* safe.

Example:

```

>>> from typing import Union, List

>>> from returns.trampolines import Trampoline, trampoline

>>> @trampoline

... def accumulate(

...     numbers: List[int],

...     acc: int = 0,

... ) -> Union[int, Trampoline[int]]:

...    if not numbers:

...        return acc

...    number = number = numbers.pop()

...    return Trampoline(accumulate, numbers, acc + number)

>>> assert accumulate([1, 2]) == 3

>>> assert accumulate([1, 2, 3]) == 6

```

The following function is still fully type-safe:

- `Trampoline` object uses `ParamSpec` to be sure that passed arguments are correct

- Final return type of the function is narrowed to contain only an original type (without `Trampoline` implementation detail)

### API Reference[¶](#module-returns.trampolines "Permalink to this heading")

*final class* Trampoline(*func*, */*, *\*args*, *\*\*kwargs*)[[source]](_modules/returns/trampolines.html#Trampoline)[¶](#returns.trampolines.Trampoline "Permalink to this definition")

Bases: `Generic`[`\_ReturnType`]

Represents a wrapped function call.

Primitive to convert recursion into an actual object.

Parameters:

* **func** (`Callable`[[`ParamSpec`(`\_FuncParams`)], `TypeVar`(`\_ReturnType`)]) –

* **args** (`ParamSpecArgs`) –

* **kwargs** (`ParamSpecKwargs`) –

func[¶](#returns.trampolines.Trampoline.func "Permalink to this definition")

args[¶](#returns.trampolines.Trampoline.args "Permalink to this definition")

kwargs[¶](#returns.trampolines.Trampoline.kwargs "Permalink to this definition")

trampoline(*func*)[[source]](_modules/returns/trampolines.html#trampoline)[¶](#returns.trampolines.trampoline "Permalink to this definition")

Convert functions using recursion to regular functions.

Trampolines allow to unwrap recursion into a regular `while` loop,

which does not raise any `RecursionError` ever.

Since python does not have TCO (tail call optimization),

we have to provide this helper.

This is done by wrapping real function calls into

[`returns.trampolines.Trampoline`](#returns.trampolines.Trampoline "returns.trampolines.Trampoline") objects:

```

>>> from typing import Union

>>> from returns.trampolines import Trampoline, trampoline

>>> @trampoline

... def get\_factorial(

...     for\_number: int,

...     current\_number: int = 0,

...     acc: int = 1,

... ) -> Union[int, Trampoline[int]]:

...     assert for\_number >= 0

...     if for\_number <= current\_number:

...         return acc

...     return Trampoline(

...         get\_factorial,

...         for\_number,

...         current\_number=current\_number + 1,

...         acc=acc \* (current\_number + 1),

...     )

>>> assert get\_factorial(0) == 1

>>> assert get\_factorial(3) == 6

>>> assert get\_factorial(4) == 24

```

See also

* eli.thegreenplace.net/2017/on-recursion-continuations-and-trampolines

* <https://en.wikipedia.org/wiki/Tail_call>

Parameters:

**func** (`Callable`[[`ParamSpec`(`\_FuncParams`)], `Union`[`TypeVar`(`\_ReturnType`), [`Trampoline`](#returns.trampolines.Trampoline "returns.trampolines.Trampoline")[`TypeVar`(`\_ReturnType`)]]]) – 

Return type:

`Callable`[[`ParamSpec`(`\_FuncParams`)], `TypeVar`(`\_ReturnType`)]

Primitive types[¶](#primitive-types "Permalink to this heading")

----------------------------------------------------------------

We have several utility types that we use for our containers,

that can also help end users as well.

### Fold[¶](#fold "Permalink to this heading")

You can use all power of declarative loops in your app with `Fold`.

```

>>> from returns.iterables import Fold

>>> from returns.io import IO

>>> items = [IO(1), IO(2), IO(3)]

>>> assert Fold.loop(

...     items,

...     IO(''),

...     lambda num: lambda text: text + str(num),

... ) == IO('123')

```

There are also other helpful methods as well.

See [`returns.iterables.AbstractFold`](#returns.iterables.AbstractFold "returns.iterables.AbstractFold").

We also ship [`AbstractFold`](#returns.iterables.AbstractFold "returns.iterables.AbstractFold"),

where you can change how `loop` (or any other) method works.

For example, for performance reasons.

Let’s say you have a big number of

[`RequiresContext`](index.html#returns.context.requires_context.RequiresContext "returns.context.requires_context.RequiresContext") instances

and you want to do the same thing string concatenation we have shown above.

You might face recursion problems with it:

```

>>> import sys

>>> from returns.context import Reader

>>> from returns.iterables import Fold

>>> items = [Reader.from\_value(num) for num in range(sys.getrecursionlimit())]

>>> Fold.loop(items, Reader.from\_value(0), lambda x: lambda y: x + y)(...)

Traceback (most recent call last):

 ...

RecursionError: ...

```

So, let’s change how it works for this specific type:

```

>>> from returns.iterables import AbstractFold

>>> class ContextAwareFold(AbstractFold):

...     @classmethod

...     def \_loop(cls, iterable, acc, function, concat, deps=None):

...         wrapped = acc.from\_value(function)

...         for current in iterable:

...             assert isinstance(current, Reader)

...             acc = Reader.from\_value(concat(current, acc, wrapped)(deps))

...         return acc

```

Note

Don’t forget to add typing annotations to your real code!

This is just an example.

And now let’s test that it works without recursion:

```

>>> items = [Reader.from\_value(num) for num in range(sys.getrecursionlimit())]

>>> assert ContextAwareFold.loop(

...    items, Reader.from\_value(0), lambda x: lambda y: x + y,

... )(...) == sum(range(sys.getrecursionlimit()))

```

And no error will be produced! We now don’t use recursion inside.

Consider this way of doing things as a respected hack.

### Immutable[¶](#immutable "Permalink to this heading")

This class is useful when you need

to make some instances immutable

(like [our containers are immutable](index.html#immutability)).

### API Reference[¶](#api-reference "Permalink to this heading")

#### Iterables[¶](#iterables "Permalink to this heading")

 classDiagram

 AbstractFold <|-- Fold

 

*class* AbstractFold[[source]](_modules/returns/iterables.html#AbstractFold)[¶](#returns.iterables.AbstractFold "Permalink to this definition")

Bases: `object`

A collection of different helpers to write declarative `Iterable` actions.

Allows to work with iterables.

Implementation

`AbstractFold` and `Fold` types are special.

They have double definition for each method: public and protected ones.

Why?

Because you cannot override `@kinded` method due to a `mypy` bug.

So, there are two opportunities for us here:

1. Declare all method as `@final` and do not allow to change anything

2. Use delegation to protected unkinded methods

We have chosen the second way! Here’s how it works:

1. Public methods are `@kinded` for better typing and cannot be overridden

2. Protected methods are unkinded and can be overridden in subtyping

Now, if you need to make a change into our implementation,

then you can subclass `Fold` or `AbstractFold` and then

change an implementation of any unkinded protected method.

*final classmethod* loop(*iterable*, *acc*, *function*)[[source]](_modules/returns/iterables.html#AbstractFold.loop)[¶](#returns.iterables.AbstractFold.loop "Permalink to this definition")

Allows to make declarative loops for any `ApplicativeN` subtypes.

Quick example:

```

>>> from typing import Callable

>>> from returns.maybe import Some

>>> from returns.iterables import Fold

>>> def sum\_two(first: int) -> Callable[[int], int]:

...     return lambda second: first + second

>>> assert Fold.loop(

...     [Some(1), Some(2), Some(3)],

...     Some(10),

...     sum\_two,

... ) == Some(16)

```

Looks like `foldl` in some other languages with some more specifics.

See: <https://philipschwarz.dev/fpilluminated/?page_id=348#bwg3/137>

![https://i.imgur.com/Tza1isS.jpg](https://i.imgur.com/Tza1isS.jpg)

Is also quite similar to `reduce`.

Public interface for `\_loop` method. Cannot be modified directly.

Parameters:

* **iterable** (`Iterable`[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ApplicativeKind`, bound= [`ApplicativeN`](index.html#returns.interfaces.applicative.ApplicativeN "returns.interfaces.applicative.ApplicativeN")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]) –

* **acc** ([`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ApplicativeKind`, bound= [`ApplicativeN`](index.html#returns.interfaces.applicative.ApplicativeN "returns.interfaces.applicative.ApplicativeN")), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) –

* **function** (`Callable`[[`TypeVar`(`\_FirstType`)], `Callable`[[`TypeVar`(`\_UpdatedType`)], `TypeVar`(`\_UpdatedType`)]]) –

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ApplicativeKind`, bound= [`ApplicativeN`](index.html#returns.interfaces.applicative.ApplicativeN "returns.interfaces.applicative.ApplicativeN")), `TypeVar`(`\_UpdatedType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

*final classmethod* collect(*iterable*, *acc*)[[source]](_modules/returns/iterables.html#AbstractFold.collect)[¶](#returns.iterables.AbstractFold.collect "Permalink to this definition")

Transforms an iterable of containers into a single container.

Quick example for regular containers:

```

>>> from returns.io import IO

>>> from returns.iterables import Fold

>>> items = [IO(1), IO(2)]

>>> assert Fold.collect(items, IO(())) == IO((1, 2))

```

If container can have failed values,

then this strategy fails on any existing failed like type.

It is enough to have even a single failed value in iterable

for this type to convert the whole operation result to be a failure.

Let’s see how it works:

```

>>> from returns.result import Success, Failure

>>> from returns.iterables import Fold

>>> empty = []

>>> all\_success = [Success(1), Success(2), Success(3)]

>>> has\_failure = [Success(1), Failure('a'), Success(3)]

>>> all\_failures = [Failure('a'), Failure('b')]

>>> acc = Success(())  # empty tuple

>>> assert Fold.collect(empty, acc) == Success(())

>>> assert Fold.collect(all\_success, acc) == Success((1, 2, 3))

>>> assert Fold.collect(has\_failure, acc) == Failure('a')

>>> assert Fold.collect(all\_failures, acc) == Failure('a')

```

If that’s now what you need, check out

[`collect\_all()`](#returns.iterables.AbstractFold.collect_all "returns.iterables.AbstractFold.collect_all")

to force collect all non-failed values.

Public interface for `\_collect` method. Cannot be modified directly.

Parameters:

* **iterable** (`Iterable`[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ApplicativeKind`, bound= [`ApplicativeN`](index.html#returns.interfaces.applicative.ApplicativeN "returns.interfaces.applicative.ApplicativeN")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]) –

* **acc** ([`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ApplicativeKind`, bound= [`ApplicativeN`](index.html#returns.interfaces.applicative.ApplicativeN "returns.interfaces.applicative.ApplicativeN")), `Tuple`[`TypeVar`(`\_FirstType`), `...`], `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) –

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_ApplicativeKind`, bound= [`ApplicativeN`](index.html#returns.interfaces.applicative.ApplicativeN "returns.interfaces.applicative.ApplicativeN")), `Tuple`[`TypeVar`(`\_FirstType`), `...`], `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

*final classmethod* collect\_all(*iterable*, *acc*)[[source]](_modules/returns/iterables.html#AbstractFold.collect_all)[¶](#returns.iterables.AbstractFold.collect_all "Permalink to this definition")

Transforms an iterable of containers into a single container.

This method only works with `FailableN` subtypes,

not just any `ApplicativeN` like [`collect()`](#returns.iterables.AbstractFold.collect "returns.iterables.AbstractFold.collect").

Strategy to extract all successful values

even if there are failed values.

If there’s at least one successful value

and any amount of failed values,

we will still return all collected successful values.

We can return failed value for this strategy only in a single case:

when default element is a failed value.

Let’s see how it works:

```

>>> from returns.result import Success, Failure

>>> from returns.iterables import Fold

>>> empty = []

>>> all\_success = [Success(1), Success(2), Success(3)]

>>> has\_failure = [Success(1), Failure('a'), Success(3)]

>>> all\_failures = [Failure('a'), Failure('b')]

>>> acc = Success(())  # empty tuple

>>> assert Fold.collect\_all(empty, acc) == Success(())

>>> assert Fold.collect\_all(all\_success, acc) == Success((1, 2, 3))

>>> assert Fold.collect\_all(has\_failure, acc) == Success((1, 3))

>>> assert Fold.collect\_all(all\_failures, acc) == Success(())

>>> assert Fold.collect\_all(empty, Failure('c')) == Failure('c')

```

If that’s now what you need, check out [`collect()`](#returns.iterables.AbstractFold.collect "returns.iterables.AbstractFold.collect")

to collect only successful values and fail on any failed ones.

Public interface for `\_collect\_all` method.

Cannot be modified directly.

Parameters:

* **iterable** (`Iterable`[[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_FailableKind`, bound= [`FailableN`](index.html#returns.interfaces.failable.FailableN "returns.interfaces.failable.FailableN")), `TypeVar`(`\_FirstType`), `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]]) –

* **acc** ([`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_FailableKind`, bound= [`FailableN`](index.html#returns.interfaces.failable.FailableN "returns.interfaces.failable.FailableN")), `Tuple`[`TypeVar`(`\_FirstType`), `...`], `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]) –

Return type:

[`KindN`](index.html#returns.primitives.hkt.KindN "returns.primitives.hkt.KindN")[`TypeVar`(`\_FailableKind`, bound= [`FailableN`](index.html#returns.interfaces.failable.FailableN "returns.interfaces.failable.FailableN")), `Tuple`[`TypeVar`(`\_FirstType`), `...`], `TypeVar`(`\_SecondType`), `TypeVar`(`\_ThirdType`)]

*class* Fold[[source]](_modules/returns/iterables.html#Fold)[¶](#returns.iterables.Fold "Permalink to this definition")

Bases: [`AbstractFold`](#returns.iterables.AbstractFold "returns.iterables.AbstractFold")

Concrete implementation of `AbstractFold` of end users.

Use it by default.

#### Types[¶](#types "Permalink to this heading")

 classDiagram

 AttributeError <|-- ImmutableStateError

 

*class* Immutable[[source]](_modules/returns/primitives/types.html#Immutable)[¶](#returns.primitives.types.Immutable "Permalink to this definition")

Bases: `object`

Helper type for objects that should be immutable.

When applied, each instance becomes immutable.

Nothing can be added or deleted from it.

```

>>> from returns.primitives.types import Immutable

>>> class MyModel(Immutable):

...     ...

>>> model = MyModel()

>>> model.prop = 1

Traceback (most recent call last):

 ...

returns.primitives.exceptions.ImmutableStateError

```

See [`returns.primitives.container.BaseContainer`](index.html#returns.primitives.container.BaseContainer "returns.primitives.container.BaseContainer") for examples.

#### Exceptions[¶](#exceptions "Permalink to this heading")

 classDiagram

 AttributeError <|-- ImmutableStateError

 Exception <|-- UnwrapFailedError

 

*exception* UnwrapFailedError(*container*)[[source]](_modules/returns/primitives/exceptions.html#UnwrapFailedError)[¶](#returns.primitives.exceptions.UnwrapFailedError "Permalink to this definition")

Bases: `Exception`

Raised when a container can not be unwrapped into a meaningful value.

Parameters:

**container** ([`Unwrappable`](index.html#returns.interfaces.unwrappable.Unwrappable "returns.interfaces.unwrappable.Unwrappable")) – 

halted\_container[¶](#returns.primitives.exceptions.UnwrapFailedError.halted_container "Permalink to this definition")

*exception* ImmutableStateError[[source]](_modules/returns/primitives/exceptions.html#ImmutableStateError)[¶](#returns.primitives.exceptions.ImmutableStateError "Permalink to this definition")

Bases: `AttributeError`

Raised when a container is forced to be mutated.

It is a sublclass of `AttributeError` for two reasons:

1. It seems kinda reasonable to expect `AttributeError`

on attribute modification

2. It is used inside `typing.py` this way,

we do have several typing features that requires that behaviour

See: <https://github.com/dry-python/returns/issues/394>

Development tooling[¶](#development-tooling "Permalink to this heading")

------------------------------------------------------------------------

### Tracing Failures[¶](#tracing-failures "Permalink to this heading")

Sometimes we want to trace where the `Failure` has occurred in our system,

`returns` provide a way to trace those failures.

By default tracing is disabled.

The trace is accessible by [`trace`](index.html#returns.result.Result.trace "returns.result.Result.trace") property

that is available for `Result`, `IOResult` containers. It’s basically a list

containing all `inspect.FrameInfo` objects from the call stack when the

`Failure` was originally created.

To enable it you can use

[`collect\_traces`](#returns.primitives.tracing.collect_traces "returns.primitives.tracing.collect_traces").

See examples below:

You can use it as a context manager:

```

>>> from inspect import FrameInfo

>>> from returns.result import Failure, Result

>>> from returns.primitives.tracing import collect\_traces

>>> def get\_failure(argument: str) -> Result[str, str]:

...     return Failure(argument)

>>> non\_traced\_failure = get\_failure('Normal Failure')

>>> with collect\_traces():

...     traced\_failure = get\_failure('Traced Failure')

>>> assert non\_traced\_failure.trace is None

>>> assert isinstance(traced\_failure.trace, list)

>>> assert all(isinstance(trace\_line, FrameInfo) for trace\_line in traced\_failure.trace)

>>> for trace\_line in traced\_failure.trace:

...     print(f"{trace\_line.filename}:{trace\_line.lineno} in `{trace\_line.function}`") 

...

/returns/returns/result.py:529 in `Failure`

/example\_folder/example.py:5 in `get\_failure`

/example\_folder/example.py:1 in `<module>`

```

Or as a decorator:

```

>>> from inspect import FrameInfo

>>> from returns.io import IOFailure, IOResult

>>> from returns.result import Failure, Result

>>> from returns.primitives.tracing import collect\_traces

>>> @collect\_traces

... def traced\_function(value: str) -> IOResult[str, str]:

...     return IOFailure(value)

>>> non\_traced\_failure = Failure('Normal Failure')

>>> traced\_failure = traced\_function('Traced Failure')

>>> assert non\_traced\_failure.trace is None

>>> assert isinstance(traced\_failure.trace, list)

>>> assert all(isinstance(trace\_line, FrameInfo) for trace\_line in traced\_failure.trace)

>>> for trace\_line in traced\_failure.trace:

...     print(f"{trace\_line.filename}:{trace\_line.lineno} in `{trace\_line.function}`") 

...

/returns/returns/result.py:525 in `Failure`

/returns/returns/io.py:852 in `IOFailure`

/example\_folder/example.py:7: in `traced\_function`

/usr/lib/python3.8/contextlib.py:75 in `inner`

/example\_folder/example.py:1 in `<module>`

```

Warning

Activating trace can make your program noticeably slower if it has many points where `Failure` is often created.

Warning

`collect\_traces` is not thread safe, beware to use it with threading!

Warning

Traces are meant to be used during development only.

### API Reference[¶](#module-returns.primitives.tracing "Permalink to this heading")

collect\_traces(*function=None*)[[source]](_modules/returns/primitives/tracing.html#collect_traces)[¶](#returns.primitives.tracing.collect_traces "Permalink to this definition")

Context Manager/Decorator to active traces collect to the Failures.

```

>>> from inspect import FrameInfo

>>> from returns.io import IOResult

>>> from returns.result import Result

>>> from returns.primitives.tracing import collect\_traces

>>> with collect\_traces():

...     traced\_failure = Result.from\_failure('Traced Failure')

>>> non\_traced\_failure = IOResult.from\_failure('Non Traced Failure')

>>> assert non\_traced\_failure.trace is None

>>> assert isinstance(traced\_failure.trace, list)

>>> assert all(isinstance(trace\_line, FrameInfo) for trace\_line in traced\_failure.trace)

>>> for trace\_line in traced\_failure.trace:

...     print(  

...         '{0}:{1} in `{2}`'.format(

...             trace\_line.filename,

...             trace\_line.lineno,

...             trace\_line.function,

...         ),

...     )

...

/returns/returns/result.py:525 in `Failure`

/returns/returns/result.py:322 in `from\_failure`

/example\_folder/example.py:1 in `<module>`

```

Parameters:

**function** (`Optional`[`TypeVar`(`\_FunctionType`, bound= `Callable`)]) – 

Return type:

`Union`[`TypeVar`(`\_FunctionType`, bound= `Callable`), `ContextManager`[`None`]]

mypy plugin[¶](#mypy-plugin "Permalink to this heading")

--------------------------------------------------------

We provide a custom `mypy` plugin to fix existing issues,

provide new awesome features,

and improve type-safety of things developers commonly use.

### Installation[¶](#installation "Permalink to this heading")

You will need to install `mypy` separately.

It is not bundled with `returns`.

To install any `mypy` plugin add it

to the `plugins` section of the config file (`setup.cfg` or `mypy.ini`):

```

[mypy]

plugins =

 returns.contrib.mypy.returns\_plugin

```

Or in `pyproject.toml`:

```

[tool.mypy]

plugins = ["returns.contrib.mypy.returns\_plugin"]

```

We recommend to always add our plugin as the first one in chain.

### Configuration[¶](#configuration "Permalink to this heading")

You can have a look at the suggested `mypy`

[configuration](https://github.com/dry-python/returns/blob/master/setup.cfg)

in our own repository.

You can also use [nitpick](https://wemake-python-stylegui.de/en/latest/pages/usage/integrations/nitpick.html)

tool to enforce the same `mypy` configuration for all your projects.

We recommend to use our own setup. Add this to your `pyproject.toml`:

```

[tool.nitpick]

style = "https://raw.githubusercontent.com/wemake-services/wemake-python-styleguide/master/styles/mypy.toml"

```

And use `flake8` to lint that configuration

defined in the setup matches yours.

This will allow to keep them in sync with the upstream.

### Supported features[¶](#supported-features "Permalink to this heading")

* `kind` feature adds Higher Kinded Types (HKT) support

* `curry` feature allows to write typed curried functions

* `partial` feature allows to write typed partial application

* `flow` feature allows to write better typed functional pipelines

with `flow` function

* `pipe` feature allows to write better typed functional pipelines

with `pipe` function

* `do-notation` feature allows using [Do Notation](index.html#do-notation)

### Further reading[¶](#further-reading "Permalink to this heading")

* [Mypy official docs](https://mypy.readthedocs.io/en/stable/index.html)

* [Mypy plugins docs](https://mypy.readthedocs.io/en/stable/extending_mypy.html)

### API Reference[¶](#api-reference "Permalink to this heading")

#### Plugin definition[¶](#module-returns.contrib.mypy._consts "Permalink to this heading")

TYPED\_PARTIAL\_FUNCTION*: Final* *= 'returns.curry.partial'*[¶](#returns.contrib.mypy._consts.TYPED_PARTIAL_FUNCTION "Permalink to this definition")

Used for typed `partial` function.

TYPED\_CURRY\_FUNCTION*: Final* *= 'returns.curry.curry'*[¶](#returns.contrib.mypy._consts.TYPED_CURRY_FUNCTION "Permalink to this definition")

Used for typed `curry` decorator.

TYPED\_FLOW\_FUNCTION*: Final* *= 'returns.\_internal.pipeline.flow.flow'*[¶](#returns.contrib.mypy._consts.TYPED_FLOW_FUNCTION "Permalink to this definition")

Used for typed `flow` call.

TYPED\_PIPE\_FUNCTION*: Final* *= 'returns.\_internal.pipeline.pipe.pipe'*[¶](#returns.contrib.mypy._consts.TYPED_PIPE_FUNCTION "Permalink to this definition")

Used for typed `pipe` call.

TYPED\_KINDN*: Final* *= 'returns.primitives.hkt.KindN'*[¶](#returns.contrib.mypy._consts.TYPED_KINDN "Permalink to this definition")

Used for HKT emulation.

DO\_NOTATION\_METHODS*: Final* *= ('returns.io.IO.do', 'returns.maybe.Maybe.do', 'returns.future.Future.do', 'returns.result.Result.do', 'returns.io.IOResult.do', 'returns.future.FutureResult.do')*[¶](#returns.contrib.mypy._consts.DO_NOTATION_METHODS "Permalink to this definition")

Used for [Do Notation](index.html#do-notation).

 classDiagram

 Plugin <|-- \_ReturnsPlugin

 Custom mypy plugin to solve the temporary problem with python typing.

Important: we don’t do anything ugly here.

We only solve problems of the current typing implementation.

`mypy` API docs are here:

<https://mypy.readthedocs.io/en/latest/extending_mypy.html>

We use `pytest-mypy-plugins` to test that it works correctly, see:

<https://github.com/mkurnikov/pytest-mypy-plugins>

plugin(*version*)[[source]](_modules/returns/contrib/mypy/returns_plugin.html#plugin)[¶](#returns.contrib.mypy.returns_plugin.plugin "Permalink to this definition")

Plugin’s public API and entrypoint.

Parameters:

**version** (`str`) – 

Return type:

`Type`[`Plugin`]

#### Kind[¶](#kind "Permalink to this heading")

 classDiagram

 Enum <|-- \_KindErrors

 str <|-- \_KindErrors

 

attribute\_access(*ctx*)[[source]](_modules/returns/contrib/mypy/_features/kind.html#attribute_access)[¶](#returns.contrib.mypy._features.kind.attribute_access "Permalink to this definition")

Ensures that attribute access to `KindN` is correct.

In other words:

```

from typing import TypeVar

from returns.primitives.hkt import KindN

from returns.interfaces.mappable import MappableN

\_MappableType = TypeVar('\_MappableType', bound=MappableN)

kind: KindN[\_MappableType, int, int, int]

reveal\_type(kind.map)  # will work correctly!

```

Parameters:

**ctx** (`AttributeContext`) – 

Return type:

`Type`

dekind(*ctx*)[[source]](_modules/returns/contrib/mypy/_features/kind.html#dekind)[¶](#returns.contrib.mypy._features.kind.dekind "Permalink to this definition")

Infers real type behind `Kind` form.

Basically, it turns `Kind[IO, int]` into `IO[int]`.

The only limitation is that it works with

only `Instance` type in the first type argument position.

So, `dekind(KindN[T, int])` will fail.

Parameters:

**ctx** (`FunctionContext`) – 

Return type:

`Type`

kinded\_signature(*ctx*)[[source]](_modules/returns/contrib/mypy/_features/kind.html#kinded_signature)[¶](#returns.contrib.mypy._features.kind.kinded_signature "Permalink to this definition")

Returns the internal function wrapped as `Kinded[def]`.

Works for `Kinded` class when `\_\_call\_\_` magic method is used.

See [`returns.primitives.hkt.Kinded`](index.html#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded") for more information.

Parameters:

**ctx** (`MethodSigContext`) – 

Return type:

`CallableType`

kinded\_call(*ctx*)[[source]](_modules/returns/contrib/mypy/_features/kind.html#kinded_call)[¶](#returns.contrib.mypy._features.kind.kinded_call "Permalink to this definition")

Reveals the correct return type of `Kinded.\_\_call\_\_` method.

Turns `-> KindN[I, t1, t2, t3]` into `-> I[t1, t2, t3]`.

Also strips unused type arguments for `KindN`, so:

- `KindN[IO, int, <nothing>, <nothing>]` will be `IO[int]`

- `KindN[Result, int, str, <nothing>]` will be `Result[int, str]`

It also processes nested `KindN` with recursive strategy.

See [`returns.primitives.hkt.Kinded`](index.html#returns.primitives.hkt.Kinded "returns.primitives.hkt.Kinded") for more information.

Parameters:

**ctx** (`MethodContext`) – 

Return type:

`Type`

kinded\_get\_descriptor(*ctx*)[[source]](_modules/returns/contrib/mypy/_features/kind.html#kinded_get_descriptor)[¶](#returns.contrib.mypy._features.kind.kinded_get_descriptor "Permalink to this definition")

Used to analyze `@kinded` method calls.

We do this due to `\_\_get\_\_` descriptor magic.

Parameters:

**ctx** (`MethodContext`) – 

Return type:

`Type`

#### Curry[¶](#curry "Permalink to this heading")

 classDiagram

 

analyze(*ctx*)[[source]](_modules/returns/contrib/mypy/_features/curry.html#analyze)[¶](#returns.contrib.mypy._features.curry.analyze "Permalink to this definition")

Returns proper type for curried functions.

Parameters:

**ctx** (`FunctionContext`) – 

Return type:

`Type`

#### Partial[¶](#partial "Permalink to this heading")

 classDiagram

 

analyze(*ctx*)[[source]](_modules/returns/contrib/mypy/_features/partial.html#analyze)[¶](#returns.contrib.mypy._features.partial.analyze "Permalink to this definition")

This hook is used to make typed curring a thing in returns project.

This plugin is a temporary solution to the problem.

It should be later replaced with the official way of doing things.

One day functions will have better API and we plan

to submit this plugin into `mypy` core plugins,

so it would not be required.

Internally we just reduce the original function’s argument count.

And drop some of them from function’s signature.

Parameters:

**ctx** (`FunctionContext`) – 

Return type:

`Type`

#### Flow[¶](#flow "Permalink to this heading")

 classDiagram

 

analyze(*ctx*)[[source]](_modules/returns/contrib/mypy/_features/flow.html#analyze)[¶](#returns.contrib.mypy._features.flow.analyze "Permalink to this definition")

Helps to analyze `flow` function calls.

By default, `mypy` cannot infer and check this function call:

```

>>> from returns.pipeline import flow

>>> assert flow(

...     1,

...     lambda x: x + 1,

...     lambda y: y / 2,

... ) == 1.0

```

But, this plugin can!

It knows all the types for all `lambda` functions in the pipeline.

How?

1. We use the first passed parameter as the first argument

to the first passed function

2. We use parameter + function to check the call and reveal

types of current pipeline step

3. We iterate through all passed function and use previous

return type as a new parameter to call current function

Parameters:

**ctx** (`FunctionContext`) – 

Return type:

`Type`

#### Pipe[¶](#pipe "Permalink to this heading")

 classDiagram

 Typing `pipe` functions requires several phases.

It is pretty obvious from its usage:

1. When we pass a sequence of functions we have to reduce

the final callable type, it is require to match the `callable` protocol.

And at this point we also kinda try

to check that all pipeline functions do match,

but this is impossible to do 100% correctly at this point,

because generic functions don’t have a type argument

to infer the final result

2. When we call the function, we need to check for two things.

First, we check that passed argument fits our instance requirement.

Second, we check that pipeline functions match.

Now we have all arguments to do the real inference.

3. We also need to fix generic in method signature.

It might be broken, because we add new generic arguments and return type.

So, it is safe to reattach generic back to the function.

Here’s when it works:

```

>>> from returns.pipeline import pipe

>>> def first(arg: int) -> bool:

...     return arg > 0

>>> def second(arg: bool) -> str:

...     return 'bigger' if arg else 'not bigger'

>>> pipeline = pipe(first, second)  # `analyzed` is called

>>> assert pipeline(1) == 'bigger'  # `signature and `infer` are called

>>> assert pipeline(0) == 'not bigger'  # `signature and `infer` again

```

analyze(*ctx*)[[source]](_modules/returns/contrib/mypy/_features/pipe.html#analyze)[¶](#returns.contrib.mypy._features.pipe.analyze "Permalink to this definition")

This hook helps when we create the pipeline from sequence of funcs.

Parameters:

**ctx** (`FunctionContext`) – 

Return type:

`Type`

infer(*ctx*)[[source]](_modules/returns/contrib/mypy/_features/pipe.html#infer)[¶](#returns.contrib.mypy._features.pipe.infer "Permalink to this definition")

This hook helps when we finally call the created pipeline.

Parameters:

**ctx** (`MethodContext`) – 

Return type:

`Type`

signature(*ctx*)[[source]](_modules/returns/contrib/mypy/_features/pipe.html#signature)[¶](#returns.contrib.mypy._features.pipe.signature "Permalink to this definition")

Helps to fix generics in method signature.

Parameters:

**ctx** (`MethodSigContext`) – 

Return type:

`CallableType`

#### Do notation[¶](#do-notation "Permalink to this heading")

 classDiagram

 

analyze(*ctx*)[[source]](_modules/returns/contrib/mypy/_features/do_notation.html#analyze)[¶](#returns.contrib.mypy._features.do_notation.analyze "Permalink to this definition")

Used to handle validation and error types in [Do Notation](index.html#do-notation).

What it does?

1. For all types we ensure that only a single container type

is used in a single do-notation. We don’t allow mixing them.

2. For types with error types (like `Result`),

it inferes what possible errors types can we have.

The result is a `Union` of all possible errors.

3. Ensures that expression passed into `.do` method is literal.

4. Checks that default value is provided

if generator expression has `if` conditions inside.

Parameters:

**ctx** (`MethodContext`) – 

Return type:

`Type`

pytest plugin[¶](#pytest-plugin "Permalink to this heading")

------------------------------------------------------------

We use special `pytest` plugin to improve the testing side of this project.

For example: it is a popular request to ensure

that your container does have its error pass handled.

Because otherwise, developers might forget to do it properly.

It is impossible to fix with types, but is really simple to check with tests.

### Installation[¶](#installation "Permalink to this heading")

You will need to install `pytest` separately.

### Usage[¶](#usage "Permalink to this heading")

There’s no need to install anything special.

`pytest` will automatically find and use this plugin.

To use it in your tests, request `returns` fixture like so:

```

def test\_my\_container(returns):

    ...

```

#### assert\_equal[¶](#assert-equal "Permalink to this heading")

We have a special helper to compare containers’ equality.

It might be an easy task for two `Result` or `Maybe` containers,

but it is not very easy for two `ReaderResult` or `FutureResult` instances.

Take a look:

```

>>> from returns.result import Result

>>> from returns.context import Reader

>>> assert Result.from\_value(1) == Result.from\_value(1)

>>> Reader.from\_value(1) == Reader.from\_value(1)

False

```

So, we can use [`assert\_equal()`](#returns.primitives.asserts.assert_equal "returns.primitives.asserts.assert_equal")

or `returns.assert\_equal` method from our `pytest` fixture:

```

>>> from returns.result import Success

>>> from returns.context import Reader

>>> from returns.contrib.pytest import ReturnsAsserts

>>> def test\_container\_equality(returns: ReturnsAsserts):

...     returns.assert\_equal(Success(1), Success(1))

...     returns.assert\_equal(Reader.from\_value(1), Reader.from\_value(1))

>>> # We only run these tests manually, because it is a doc example:

>>> returns\_fixture = getfixture('returns')

>>> test\_container\_equality(returns\_fixture)

```

#### is\_error\_handled[¶](#is-error-handled "Permalink to this heading")

The first helper we define is `is\_error\_handled` function.

It tests that containers do handle error track.

```

>>> from returns.result import Failure, Success

>>> from returns.contrib.pytest import ReturnsAsserts

>>> def test\_error\_handled(returns: ReturnsAsserts):

...     assert not returns.is\_error\_handled(Failure(1))

...     assert returns.is\_error\_handled(

...         Failure(1).lash(lambda \_: Success('default value')),

...     )

>>> # We only run these tests manually, because it is a doc example:

>>> returns\_fixture = getfixture('returns')

>>> test\_error\_handled(returns\_fixture)

```

We recommend to unit test big chunks of code this way.

This is helpful for big pipelines where

you need at least one error handling at the very end.

This is how it works internally:

* Methods like `fix` and `lash` mark errors

inside the container as handled

* Methods like `map` and `alt` just copies

the error handling state from the old container to a new one,

so there’s no need to re-handle the error after these methods

* Methods like `bind` create new containers with unhandled errors

Note

We use monkeypathing of containers inside tests to make this check possible.

They are still purely functional inside.

It does not affect production code.

#### assert\_trace[¶](#assert-trace "Permalink to this heading")

Sometimes we have to know if a container is created correctly in a specific

point of our flow.

`assert\_trace` helps us to check exactly this by

identifying when a container is

created and looking for the desired function.

```

>>> from returns.result import Result, Success, Failure

>>> from returns.contrib.pytest import ReturnsAsserts

>>> def desired\_function(arg: str) -> Result[int, str]:

...     if arg.isnumeric():

...         return Success(int(arg))

...     return Failure('"{0}" is not a number'.format(arg))

>>> def test\_if\_failure\_is\_created\_at\_convert\_function(

...     returns: ReturnsAsserts,

... ):

...     with returns.assert\_trace(Failure, desired\_function):

...         Success('not a number').bind(desired\_function)

>>> def test\_if\_success\_is\_created\_at\_convert\_function(

...     returns: ReturnsAsserts,

... ):

...     with returns.assert\_trace(Success, desired\_function):

...         Success('42').bind(desired\_function)

>>> # We only run these tests manually, because it is a doc example:

>>> returns\_fixture = getfixture('returns')

>>> test\_if\_failure\_is\_created\_at\_convert\_function(returns\_fixture)

>>> test\_if\_success\_is\_created\_at\_convert\_function(returns\_fixture)

```

#### markers[¶](#markers "Permalink to this heading")

We also ship a bunch of pre-defined markers with `returns`:

* `returns\_lawful` is used to mark all tests generated

by our [hypothesis plugin](index.html#hypothesis-plugins)

### Further reading[¶](#further-reading "Permalink to this heading")

* [pytest docs](https://docs.pytest.org/en/latest/contents.html)

### API Reference[¶](#api-reference "Permalink to this heading")

 classDiagram

 BaseException <|-- \_DesiredFunctionFound

 

*final class* ReturnsAsserts(*errors\_handled*)[[source]](_modules/returns/contrib/pytest/plugin.html#ReturnsAsserts)[¶](#returns.contrib.pytest.plugin.ReturnsAsserts "Permalink to this definition")

Bases: `object`

Class with helpers assertions to check containers.

Parameters:

**errors\_handled** (`Dict`[`int`, `Any`]) – 

*static* assert\_equal(*first*, *second*, *\**, *deps=None*, *backend='asyncio'*)[[source]](_modules/returns/contrib/pytest/plugin.html#ReturnsAsserts.assert_equal)[¶](#returns.contrib.pytest.plugin.ReturnsAsserts.assert_equal "Permalink to this definition")

Can compare two containers even with extra calling and awaiting.

Parameters:

**backend** (`str`) – 

Return type:

`None`

is\_error\_handled(*container*)[[source]](_modules/returns/contrib/pytest/plugin.html#ReturnsAsserts.is_error_handled)[¶](#returns.contrib.pytest.plugin.ReturnsAsserts.is_error_handled "Permalink to this definition")

Ensures that container has its error handled in the end.

Return type:

`bool`

*static* assert\_trace(*trace\_type*, *function\_to\_search*)[[source]](_modules/returns/contrib/pytest/plugin.html#ReturnsAsserts.assert_trace)[¶](#returns.contrib.pytest.plugin.ReturnsAsserts.assert_trace "Permalink to this definition")

Ensures that a given function was called during execution.

Use it to determine where the failure happened.

Parameters:

* **trace\_type** (`TypeVar`(`\_ReturnsResultType`, bound= `Union`[ResultLikeN, `Callable`[`...`, ResultLikeN]])) –

* **function\_to\_search** (`TypeVar`(`\_FunctionType`, bound= `Callable`)) –

Return type:

`Iterator`[`None`]

pytest\_configure(*config*)[[source]](_modules/returns/contrib/pytest/plugin.html#pytest_configure)[¶](#returns.contrib.pytest.plugin.pytest_configure "Permalink to this definition")

Hook to be executed on import.

We use it define custom markers.

Return type:

`None`

returns()[[source]](_modules/returns/contrib/pytest/plugin.html#returns)[¶](#returns.contrib.pytest.plugin.returns "Permalink to this definition")

Returns class with helpers assertions to check containers.

Return type:

`Iterator`[[`ReturnsAsserts`](#returns.contrib.pytest.plugin.ReturnsAsserts "returns.contrib.pytest.plugin.ReturnsAsserts")]

assert\_equal(*first*, *second*, *\**, *deps=None*, *backend='asyncio'*)[[source]](_modules/returns/primitives/asserts.html#assert_equal)[¶](#returns.primitives.asserts.assert_equal "Permalink to this definition")

Custom `assert` function to compare two any containers.

The important note here is that

this `assert` should probably used in tests.

Not real application code.

It will call all `Reader` based containers and `await`

all `Future` based ones.

It also works recursively.

For example, `ReaderFutureResult` will be called and then awaited.

You can specify different dependencies to call your containers.

And different backends to `await` then using `anyio`.

By the way, `anyio` should be installed separately.

Parameters:

**backend** (`str`) – 

Return type:

`None`

hypothesis plugin[¶](#hypothesis-plugin "Permalink to this heading")

--------------------------------------------------------------------

We provide several extra features for Hypothesis users.

And encourage to use it together with `returns`.

### Installation[¶](#installation "Permalink to this heading")

You will need to install `hypothesis` separately.

It is not bundled with `returns`.

We also require `anyio` package for this plugin to work with async laws.

### hypothesis entrypoint[¶](#hypothesis-entrypoint "Permalink to this heading")

We support a `hypothesis` entrypoint

that is executed on `hypothesis` import.

There we are regestering all our containers as strategies.

So, you don’t have to. Example:

```

from returns.result import Result

from hypothesis import strategies as st

assert st.from\_type(Result).example()

```

This is a convenience thing only.

### strategy\_from\_container[¶](#strategy-from-container "Permalink to this heading")

We provide a utility function

to create `hypothesis` strategy from any container.

You can use it to easily register your own containers.

```

from hypothesis import strategies as st

from returns.contrib.hypothesis.containers import strategy\_from\_container

st.register\_type\_strategy(

    YourContainerClass,

    strategy\_from\_container(YourContainerClass),

)

```

You can also pass `use\_init` keyword argument

if you wish to use `\_\_init\_\_` method to instantiate your containers.

Turned off by default.

Example:

```

st.register\_type\_strategy(

    YourContainerClass,

    strategy\_from\_container(YourContainerClass, use\_init=True),

)

```

Or you can write your own `hypothesis` strategy. It is also fine.

### check\_all\_laws[¶](#check-all-laws "Permalink to this heading")

We also provide a very powerful mechanism of checking defined container laws.

It works in a combitation with “Laws as Values” feature we provide in the core.

```

from returns.contrib.hypothesis.laws import check\_all\_laws

from your.module import YourCustomContainer

check\_all\_laws(YourCustomContainer)

```

This one line of code will generate ~100 tests for all defined law

in both `YourCustomContainer` and all its super types,

including our internal ones.

We also provide a way to configure

the checking process with `settings\_kwargs`:

```

check\_all\_laws(YourCustomContainer, settings\_kwargs={'max\_examples': 500})

```

This will increase the number of generated test to 500.

We support all kwargs from `@settings`, see

[@settings docs](https://hypothesis.readthedocs.io/en/latest/settings.html).

You can also change how `hypothesis` creates instances of your container.

By default, we use `.from\_value`, `.from\_optional`, and `.from\_failure`

if we are able to find them.

But, you can also pass types without these methods,

but with `\_\_init\_\_` defined:

```

from typing import Callable, TypeVar, final

from returns.interfaces.mappable import Mappable1

from returns.primitives.container import BaseContainer

from returns.primitives.hkt import SupportsKind1

\_ValueType = TypeVar('\_ValueType')

\_NewValueType = TypeVar('\_NewValueType')

@final

class Number(

    BaseContainer,

    SupportsKind1['Number', \_ValueType],

    Mappable1[\_ValueType],

):

    def \_\_init\_\_(self, inner\_value: \_ValueType) -> None:

        super().\_\_init\_\_(inner\_value)

    def map(

        self,

        function: Callable[[\_ValueType], \_NewValueType],

    ) -> 'Number[\_NewValueType]':

        return Number(function(self.\_inner\_value))

# We want to allow ``\_\_init\_\_`` method to be used:

check\_all\_laws(Number, use\_init=True)

```

As you see, we don’t support any `from` methods here.

But, `\_\_init\_\_` would be used to generate values thanks to `use\_init=True`.

By default, we don’t allow to use `\_\_init\_\_`,

because there are different complex types

like `Future`, `ReaderFutureResult`, etc

that have complex `\_\_init\_\_` signatures.

And we don’t want to mess with them.

Warning::Checking laws is not compatible with `pytest-xdist`,

because we use a lot of global mutable state there.

Please, use `returns\_lawful` marker

to exclude them from `pytest-xdist` execution plan.

### Further reading[¶](#further-reading "Permalink to this heading")

* [Projects Extending hypothesis](https://hypothesis.readthedocs.io/en/latest/strategies.html)

### API Reference[¶](#api-reference "Permalink to this heading")

#### Types we have already registered for you[¶](#module-returns.contrib.hypothesis._entrypoint "Permalink to this heading")

Used to register all our types as hypothesis strategies.

See: <https://hypothesis.readthedocs.io/en/latest/strategies.html>

But, beware that we only register concrete types here,

interfaces won’t be registered!

REGISTERED\_TYPES*: Sequence[Type[[Lawful](index.html#returns.primitives.laws.Lawful "returns.primitives.laws.Lawful")]]* *= (<class 'returns.result.Result'>, <class 'returns.maybe.Maybe'>, <class 'returns.io.IO'>, <class 'returns.io.IOResult'>, <class 'returns.future.Future'>, <class 'returns.future.FutureResult'>, <class 'returns.context.requires\_context.RequiresContext'>, <class 'returns.context.requires\_context\_result.RequiresContextResult'>, <class 'returns.context.requires\_context\_ioresult.RequiresContextIOResult'>, <class 'returns.context.requires\_context\_future\_result.RequiresContextFutureResult'>)*[¶](#returns.contrib.hypothesis._entrypoint.REGISTERED_TYPES "Permalink to this definition")

Our types that we register in hypothesis to be working with `st.from\_type`

#### DSL to register custom containers[¶](#module-returns.contrib.hypothesis.containers "Permalink to this heading")

strategy\_from\_container(*container\_type*, *\**, *use\_init=False*)[[source]](_modules/returns/contrib/hypothesis/containers.html#strategy_from_container)[¶](#returns.contrib.hypothesis.containers.strategy_from_container "Permalink to this definition")

Creates a strategy from a container type.

Basically, containers should not support `\_\_init\_\_`

even when they have one.

Because, that can be very complex: for example `FutureResult` requires

`Awaitable[Result[a, b]]` as an `\_\_init\_\_` value.

But, custom containers pass `use\_init`

if they are not an instance of `ApplicativeN`

and do not have a working `.from\_value` method.

For example, pure `MappableN` can do that.

We also try to resolve generic arguments.

So, `Result[\_ValueType, Exception]`

will produce any value for success cases

and only exceptions for failure cases.

Parameters:

* **container\_type** (`type`[[`Lawful`](#returns.primitives.laws.Lawful "returns.primitives.laws.Lawful")]) –

* **use\_init** (`bool`) –

Return type:

`Callable`[[`type`], `SearchStrategy`]

#### DSL to define laws[¶](#dsl-to-define-laws "Permalink to this heading")

 classDiagram

 Generic <|-- Law1

 Generic <|-- Law2

 Generic <|-- Law3

 Generic <|-- Lawful

 Immutable <|-- Law

 Law <|-- Law1

 Law <|-- Law2

 Law <|-- Law3

 

law\_definition[¶](#returns.primitives.laws.law_definition "Permalink to this definition")

Special alias to define laws as functions even inside a class

*class* Law(*function*)[[source]](_modules/returns/primitives/laws.html#Law)[¶](#returns.primitives.laws.Law "Permalink to this definition")

Bases: [`Immutable`](index.html#returns.primitives.types.Immutable "returns.primitives.types.Immutable")

Base class for all laws. Does not have an attached signature.

Should not be used directly.

Use `Law1`, `Law2` or `Law3` instead.

definition*: `Callable`*[¶](#returns.primitives.laws.Law.definition "Permalink to this definition")

Function used to define this law.

*property* name*: str*[¶](#returns.primitives.laws.Law.name "Permalink to this definition")

Returns a name of the given law. Basically a name of the function.

*final class* Law1(*function*)[[source]](_modules/returns/primitives/laws.html#Law1)[¶](#returns.primitives.laws.Law1 "Permalink to this definition")

Bases: [`Law`](#returns.primitives.laws.Law "returns.primitives.laws.Law"), `Generic`[`\_TypeArgType1`, `\_ReturnType`]

Law definition for functions with a single argument.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_TypeArgType1`)], `TypeVar`(`\_ReturnType`)]) – 

*final class* Law2(*function*)[[source]](_modules/returns/primitives/laws.html#Law2)[¶](#returns.primitives.laws.Law2 "Permalink to this definition")

Bases: [`Law`](#returns.primitives.laws.Law "returns.primitives.laws.Law"), `Generic`[`\_TypeArgType1`, `\_TypeArgType2`, `\_ReturnType`]

Law definition for functions with two arguments.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_TypeArgType1`), `TypeVar`(`\_TypeArgType2`)], `TypeVar`(`\_ReturnType`)]) – 

*final class* Law3(*function*)[[source]](_modules/returns/primitives/laws.html#Law3)[¶](#returns.primitives.laws.Law3 "Permalink to this definition")

Bases: [`Law`](#returns.primitives.laws.Law "returns.primitives.laws.Law"), `Generic`[`\_TypeArgType1`, `\_TypeArgType2`, `\_TypeArgType3`, `\_ReturnType`]

Law definition for functions with three argument.

Parameters:

**function** (`Callable`[[`TypeVar`(`\_TypeArgType1`), `TypeVar`(`\_TypeArgType2`), `TypeVar`(`\_TypeArgType3`)], `TypeVar`(`\_ReturnType`)]) – 

*class* Lawful[[source]](_modules/returns/primitives/laws.html#Lawful)[¶](#returns.primitives.laws.Lawful "Permalink to this definition")

Bases: `Generic`[`\_Caps`]

Base class for all lawful classes.

Allows to smartly collect all defined laws from all parent classes.

*final classmethod* laws()[[source]](_modules/returns/primitives/laws.html#Lawful.laws)[¶](#returns.primitives.laws.Lawful.laws "Permalink to this definition")

Collects all laws from all parent classes.

Algorithm:

:rtype: `Dict`[`Type`[[`Lawful`](#returns.primitives.laws.Lawful "returns.primitives.laws.Lawful")], `Sequence`[[`Law`](#returns.primitives.laws.Law "returns.primitives.laws.Law")]]

1. First, we collect all unique parents in `\_\_mro\_\_`

2. Then we get the laws definition from each of them

3. Then we structure them in a `type: its\_laws` way

*class* LawSpecDef[[source]](_modules/returns/primitives/laws.html#LawSpecDef)[¶](#returns.primitives.laws.LawSpecDef "Permalink to this definition")

Bases: `object`

Base class for all collection of laws aka LawSpecs.

#### Plugin internals[¶](#module-returns.contrib.hypothesis.laws "Permalink to this heading")

check\_all\_laws(*container\_type*, *\**, *settings\_kwargs=None*, *use\_init=False*)[[source]](_modules/returns/contrib/hypothesis/laws.html#check_all_laws)[¶](#returns.contrib.hypothesis.laws.check_all_laws "Permalink to this definition")

Function to check all defined mathematical laws in a specified container.

Should be used like so:

```

from returns.contrib.hypothesis.laws import check\_all\_laws

from returns.io import IO

check\_all\_laws(IO)

```

You can also pass different `hypothesis` settings inside:

```

check\_all\_laws(IO, {'max\_examples': 100})

```

Note

Cannot be used inside doctests because of the magic we use inside.

See also

* <https://sobolevn.me/2021/02/make-tests-a-part-of-your-app>

* <https://mmhaskell.com/blog/2017/3/13/obey-the-type-laws>

Parameters:

* **container\_type** (`Type`[[`Lawful`](#returns.primitives.laws.Lawful "returns.primitives.laws.Lawful")]) –

* **settings\_kwargs** (`Optional`[`Dict`[`str`, `Any`]]) –

* **use\_init** (`bool`) –

Return type:

`None`

container\_strategies(*container\_type*, *\**, *settings*)[[source]](_modules/returns/contrib/hypothesis/laws.html#container_strategies)[¶](#returns.contrib.hypothesis.laws.container_strategies "Permalink to this definition")

Registers all types inside a container to resolve to a correct strategy.

For example, let’s say we have `Result` type.

It is a subtype of `ContainerN`, `MappableN`, `BindableN`, etc.

When we check this type, we need `MappableN` to resolve to `Result`.

Can be used independently from other functions.

Parameters:

* **container\_type** (`Type`[[`Lawful`](#returns.primitives.laws.Lawful "returns.primitives.laws.Lawful")]) –

* **settings** (`\_Settings`) –

Return type:

`Iterator`[`None`]

maybe\_register\_container(*container\_type*, *\**, *use\_init*)[[source]](_modules/returns/contrib/hypothesis/laws.html#maybe_register_container)[¶](#returns.contrib.hypothesis.laws.maybe_register_container "Permalink to this definition")

Temporary registers a container if it is not registered yet.

Parameters:

* **container\_type** (`Type`[[`Lawful`](#returns.primitives.laws.Lawful "returns.primitives.laws.Lawful")]) –

* **use\_init** (`bool`) –

Return type:

`Iterator`[`None`]

pure\_functions()[[source]](_modules/returns/contrib/hypothesis/laws.html#pure_functions)[¶](#returns.contrib.hypothesis.laws.pure_functions "Permalink to this definition")

Context manager to resolve all `Callable` as pure functions.

It is not a default in `hypothesis`.

Return type:

`Iterator`[`None`]

type\_vars()[[source]](_modules/returns/contrib/hypothesis/laws.html#type_vars)[¶](#returns.contrib.hypothesis.laws.type_vars "Permalink to this definition")

Our custom `TypeVar` handling.

There are several noticeable differences:

:rtype: `Iterator`[`None`]

1. We add mutable types to the tests: like `list` and `dict`

2. We ensure that values inside strategies are self-equal,

for example, `nan` does not work for us

Version history[¶](#version-history "Permalink to this heading")

----------------------------------------------------------------

We follow Semantic Versions since the `1.0.0` release.

Versions before `1.0.0` are `0Ver`-based:

incremental in minor, bugfixes only are patches.

See [0Ver](https://0ver.org/).

### 0.22.0[¶](#id1 "Permalink to this heading")

#### Features[¶](#features "Permalink to this heading")

* *Breaking*: Drops `python3.7` support

* Now requires `mypy>=1.5`

* Adds `trampolines` support

### 0.21.0[¶](#id2 "Permalink to this heading")

#### Features[¶](#id3 "Permalink to this heading")

* Now requires `mypy>=1.4`

* Adds `[compatible-mypy]` extra for installation

### 0.20.1[¶](#id4 "Permalink to this heading")

#### Bugfixes[¶](#bugfixes "Permalink to this heading")

* Fixed HKT `to\_str` example in documentation

* Fixed backward deserialization compatibility for BaseContainer

### 0.20.0[¶](#id5 "Permalink to this heading")

#### Features[¶](#id6 "Permalink to this heading")

* Now requires `mypy>=1.2`

#### Bugfixes[¶](#id7 "Permalink to this heading")

* Fixes a problem with `do-notation` and type aliases

* Fixes custom pickle protocol to handle `None` values gracefully

* Removes broken drylabs.io link in README

* Revises pointfree documentation

### 0.19.0 aka The Do Notation[¶](#aka-the-do-notation "Permalink to this heading")

#### Features[¶](#id8 "Permalink to this heading")

* Adds `do` notation

* Adds `attempt` decorator

#### Misc[¶](#misc "Permalink to this heading")

* Check `\_\_slots\_\_\ `` correctness with``slotscheck`

### 0.18.0[¶](#id9 "Permalink to this heading")

New Year Release! 🎄

#### Features[¶](#id10 "Permalink to this heading")

* Now requires `typing\_extensions>=4.0`

* Now requires `mypy>=0.930`

* Removes plugin for `@safe`, `@maybe`, `@future`, etc.

Because we now use `ParamSpec` type to properly type decorators

#### Bugfixes[¶](#id11 "Permalink to this heading")

* Fixes `\_\_slots\_\_` not being set properly in containers and their base classes

* Fixes patching of containers in pytest plugin not undone after each test

### 0.17.0[¶](#id12 "Permalink to this heading")

#### Features[¶](#id13 "Permalink to this heading")

* Enables Pattern Matching support for `Result` containers

* Enables Pattern Matching support for `Maybe` container

* Enables Pattern Matching support for `IOResult` container

* Improves `hypothesis` plugin, now we detect

when type cannot be constructed and give a clear error message

* Adds the option to pass what exceptions `@safe` will handle

### 0.16.0[¶](#id14 "Permalink to this heading")

#### Features[¶](#id15 "Permalink to this heading")

* Makes `\_Nothing` a singleton

* Refactor `flow` function to be faster

#### Bugfixes[¶](#id16 "Permalink to this heading")

* Fixes that `assert\_trace` was not catching containers

from `@safe`-wrapped functions

#### Misc[¶](#id17 "Permalink to this heading")

* Fixes typos in documentation

### 0.15.0 aka The initial HKT release[¶](#aka-the-initial-hkt-release "Permalink to this heading")

#### Features[¶](#id18 "Permalink to this heading")

* Adds Higher Kinded Types partial support

* **Breaking**: drops `python3.6` support

* **Breaking**: makes our `mypy` plugin not optional, but required!

* **Breaking**: changes all `RequiresContext`-based type arguments order,

previously we used to specify `\_EnvType` as the first type argument,

now it is the last one. This is done to respect new HKT rules

* **Breaking**: renames `.rescue` to `.lash`

* **Breaking**: removes all old interfaces from `primitives/interfaces.py`,

use new typeclasses instead

* **Breaking**: `Maybe` is fully reworked to be lawful

* **Breaking**: removes `value\_or` pointfree method,

because it is impossible to express with HKT

* **Breaking**: removes `.value\_or`, `.unwrap`, and `.failure` methods

from `FutureResult` and `RequiresContext`-based types,

because we do require these methods to raise an exception on failure,

but these methods were lazy and did not raise the required exception

* **Breaking**: changes how `is\_successful` is typed:

now we allow any `Unwrappable` interface instances there,

including custom ones

* **Breaking**: changes `UnwrapFailedError` constructor,

now it does accept an `Unwrappable` instance instead of a `BaseContainer`

* **Breaking**: removes `.fix` method from all containers,

also removes `fix` pointfree function

* **Breaking**: Removes `coalesce` function,

because it is impossible to properly type it

* **Breaking**: Removes all `Context\*` based types with `.ask()` method,

use new `.ask()` methods on the `Reader`-based containers

* **Breaking**: Now `Future` and `FutureResult` can be awaited multiple times

* **Breaking**: Removes `.unify()` method from several containers,

use `unify()` pointfree function instead

* **Breaking**: Removes `.from\_iterable` method from all containers,

instead adds better `iterables` support,

we now have `returns.iterables` module with `Fold` helper

* **Breaking**: Renames property `empty` to `no\_args` of

all `RequiresContext`-based classes

* Adds new public interfaces: see `returns.interfaces`

* Adds `methods` package with several helpful things inside

* Adds `FutureSuccess` and `FutureFailure` unit functions

to be similar to `Result` and `IOResult`

* Adds `.swap` method to `Result`, `IOResult`, `FutureResult`,

and other result based containers

* Adds `.modify\_env` method to all `RequiresContext\*` types

* Adds `.rescue` to `Maybe`

* Adds `.equals` methods to types that can be compared directly:

`Result`, `Maybe`, `IO`, `IOResult`

* Adds missing `from\_requires\_context\_future\_result` to `RequiresContext`

* Adds `.from\_optional` and `.bind\_optional` to `Maybe` container

* Adds `\_\_slots\_\_` to `UnwrapFailedError` with `halted\_container`

* Changes `flatten` to work with `KindN` and any possible container

* Adds a helper to test traces to our `pytest` plugin

* Adds `cond` function to `pointfree` and `methods` packages

* Adds `compose\_result` HKT method and pointfree function

* Adds `unify` HKT pointfree function

* Adds `bimap` pointfree function

* Adds `unwrap\_or\_failure` function to `methods` package

* Adds `collect\_trace` helper function for better development experience

* Adds `hypothesis` integration and pre-defined “monad laws as values”

* Adds `assert\_equal` method to our `pytest` plugin

#### Bugfixes[¶](#id19 "Permalink to this heading")

* **Breaking**: fixes serious typing issue and changes how `flow` works

* **Breaking**: fixes serious typing issue and changes how `pipe` works,

now it has a hard limit of 20 parameters

* Fixes that `RequiresContextFutureResult` was not supported by `pytest` plugin

* Fixes incorrect `partial` behaviour in an edge case, #618

* Fixes that `.apply` method of `IOResult` was working incorrectly,

it was returning `IOFailure(2)`

as a result of `IOFailure(1).apply(IOFailure(2))`

* Fixes bug that `safe(tap(...))` was revealing invalid types sometimes

#### Misc[¶](#id20 "Permalink to this heading")

* Adds a lot of new typetests

* Checks that now all math laws are checked for all types

* Changes docs structure, adds new `Interfaces`, `HKT`, and `Methods` pages

* Changed `\_\_str\_\_` method in `BaseContainer` class to `\_\_repr\_\_` method

* Adds `Quickstart` guide

### 0.14.0[¶](#id21 "Permalink to this heading")

#### Features[¶](#id22 "Permalink to this heading")

* **Breaking**: renames mypy plugin from `decorator\_plugin` to `returns\_plugin`

because of a complete rewrite and lots of new features

* **Breaking**: changes `@safe`, `@impure`, `impure\_safe`, `@maybe` semantics:

they do not work with `async` functions anymore;

now you are forced to use `Future` and its helpers

to work with `async` functions

* **Breaking**: renames `Maybe.new` to `Maybe.from\_value`.

Because all our other containers support this protocol.

Only `Maybe` was different, sorry for that!

* **Breaking**: renames `.from\_success()` to `.from\_value()`,

there’s no need in two separate methods

* **Breaking**: renames `.from\_successful\_io()` to `.from\_io()`,

there’s no need in two separate methods

* **Breaking**: renames `.from\_successful\_context()` to `.from\_context()`,

there’s no need in two separate methods

* **Breaking**: since we now support `.apply()` method,

there’s no more need in `\*\_squash` converters, they are removed

* **Breaking**: renamed `Instanceable` to `Applicative`

* **Breaking**: changes `.from\_io` and `.from\_failed\_io` of `IOResult`

to return `Any` instead of `NoReturn` unfilled type

* **Breaking**: removes `.lift` and `.lift\_\*` methods from all containers,

use `map\_`, `bind\_result`, `bind\_io`, and other pointfree helpers instead

* **Breaking**: removes `@pipeline` function. It was a mistake:

it does not work with mixed container types,

it does not type failures properly,

it does not work with `IO` and `Future`,

it enforces to write imperative code in a functional codebase.

Use `flow` instead

* Adds typed `partial` and `curry` mypy plugins!

* Adds typed `flow` plugin, now it can accept any number of arguments,

it now also has **excellent** type inference

* Adds typed `pipe` plugin, now it can accept any number of arguments,

it now also has good type inference

* Adds `managed` pipeline function that is useful

for working with stateful computations

* Adds typed `map\_`, `fix`, and `alt` pointfree functions

* Adds typed `bind\_result`, `bind\_io`, `bind\_ioresult`,

`bind\_context`, `bind\_context\_result`, `bind\_future`,

`bind\_async`, and `bind\_awaitable` pointfree functions

* Adds typed `bind\_async\_future` and `bind\_async\_future\_result`

pointfree functions

* Adds typed `unify` pointfree function

* Adds typed `apply` pointfree function

* Adds typed `value\_or` pointfree function

* Adds `pytest` plugin with the ability to tests error handling

* Adds `Future` container to easily work with `async` functions

* Adds `FutureResult` container to easily work

with `async` function that might fail

* Adds `RequiresContextFutureResult` container

* Adds `ReaderFutureResult` alias for `RequiresContextFutureResult`

* Adds `RequiresContextFutureResultE` and `ReaderFutureResultE` aliases

* Adds `Future`, `FutureResult` and `RequiresContextFutureResult`

support for all existing pointfree functions

* Adds `bind\_io` method to `IOResult`

* Adds `bind\_io` method to `RequiresContextIOResult`

* Adds `or\_else` method to `Maybe`

* Adds `.from\_io` and `.from\_failed\_io` to `RequiresContextIOResult`

* Syncs naming in `from\_\*` methods, now all parameters are named `inner\_value`

* Adds `not\_` composition helper

* Adds `flatten` support for `Future`,

`FutureResult` and `RequiresContextFutureResult`

* Adds `\_\_copy\_\_` and `\_\_deepcopy\_\_` magic methods to `Immutable` class

* Speeds up `is\_successful` function

* Makes all `Context` context helpers abstract,

so you cannot create new instances of this class,

also adds `\_\_slots\_\_` to these classes

* Improves `RequiresContext\*` types with `NoDeps` where it is logically true

#### Bugfixes[¶](#id23 "Permalink to this heading")

* Fixes that `@safe` decorator was generating incorrect signatures

for functions with `Any`

* Fixes that `.rescue()` of `RequiresContextResult` was returning `Any`

* Fixes that `.rescue()` of `RequiresContextIOResult` was returning `Any`

* Fixes that `RequiresContextResult` and `RequiresContextIOResult`

were not `final`

* Fixes that `ImmutableStateError` was not a subclass of `AttributeError`

* Fixes that `IOResult` was not showing `str` representation

of wrapped `inner\_value`

#### Misc[¶](#id24 "Permalink to this heading")

* Replaces `pytest-asyncio` with `anyio` plugin,

now we test compatibility with any IO stack: `asyncio`, `trio`, `curio`

* Updates lots of dependencies

* Adds lots of new tests

* Updates lots of docs

* Removes “IO marker” name from docs in favor for “IO container”,

it is not special at all. Why would we call it differently?

### 0.13.0[¶](#id25 "Permalink to this heading")

#### Features[¶](#id26 "Permalink to this heading")

* **Breaking**: renames `join` to `flatten`, sorry!

* **Breaking**: renames `box` to `bind` and moves it to `returns.pointfree`

* **Breaking**: removes `Maybe.rescue` and `Maybe.fix` methods

* **Breaking**: renames `io\_squash` to `squash\_io`

and moves it to `returns.converters`

* **Breaking**: moves all interfaces from `returns.primitives.container` to

`returns.primitives.interfaces`

* Adds `rescue` pointfree function

* Adds `ResultE` alias for `Result[..., Exception]`

* Adds `RequiresContext` container and `Context` helper class

* Adds `RequiresContext` support for `bind` pointfree function

* Adds `RequiresContext` support for `flatten` function

* Adds `RequiresContextResult` container

* Adds `RequiresContextResultE` alias

* Adds `ReaderResult` and `ReaderResultE` aliases

for `RequiresContextResult[..., ..., Exception]`

* Adds `RequiresContextResult` support for `bind` and `rescue`

* Adds `RequiresContextResult` support for `flatten`

* Adds `IOResult` helper to work better with `IO[Result[a, b]]`

* Adds `IOResultE` alias for `IOResult[a, Exception]`

* Adds `IOResult` support for `bind`

* Adds `IOResult` support for `flatten`

* Adds `IOResult` support for `@pipeline`

* Adds `IOResult` support for `coalesce`

* Adds `IOResult` support for `is\_successful`

* Adds `RequiresContextIOResult` container

* Adds `RequiresContextIOResultE` alias

* Adds `ReaderIOResult` and `ReaderIOResultE` aliases

for `RequiresContextIOResult[..., ..., Exception]`

* Adds `RequiresContextIOResult` support for `bind` and `rescue`

* Adds `RequiresContextIOResult` support for `flatten`

* Adds `Result.lift`, `Maybe.lift`, `RequiresContext.lift`,

and `RequiresContextResult.lift` functions in addition to `IO.lift`

* Adds `Immutable` primitive type

* Adds `Unitable` protocol and `.from\_success()` and `.from\_failure()`

methods for all `Result` related classes

* Adds `Instanceable` protocol and `.from\_value()` method

for `IO` and `RequiresContext`

* Adds `flow` function, which is similar to `pipe`

* Adds `swap` converter for `Result` and `IOResult`

* Adds `squash\_context` function to squash `RequiresContext` similar to `IO`

#### Bugfixes[¶](#id27 "Permalink to this heading")

* Now `Success` and `Failure` (both `io` and pure) return `Any` and not `NoReturn`

* Fixes how `flatten` works, also adds more tests and docs about `Failure` case

* Fixes `Unwrappable` type being parametrized with only one `TypeVar`

* Changes `Success` and `Failure` to return `Any` instead of `NoReturn`

#### Misc[¶](#id28 "Permalink to this heading")

* Updates `poetry` version in `travis`

* Improves `pipe` docs with `lambda` and `Generic` problem

* Improves docs in several places

* Now examples in docs tries to be docstests where possible

* Changes how tests are checked with `mypy` in CI

### 0.12.0[¶](#id29 "Permalink to this heading")

#### Features[¶](#id30 "Permalink to this heading")

* **Breaking**: now `@pipeline` requires a container type when created:

`@pipeline(Result)` or `@pipeline(Maybe)`

* `Maybe` and `Result` now has `success\_type` and `failure\_type` aliases

* Adds `Result.unify` utility method for better error type composition

* We now support `dry-python/classes` as a first-class citizen

* Adds `io\_squash` to squash several `IO` containers into one container

with a tuple inside, currently works with `9` containers max at a time

* Adds `untap` function which does convert return type to `None`

#### Bugfixes[¶](#id31 "Permalink to this heading")

* Fixes that containers were not usable with `multiprocessing`

* Changes the inheritance order, now `BaseContainer` is the first child

* Fixes that `Nothing` had incorrect docstrings

#### Misc[¶](#id32 "Permalink to this heading")

* Now `generated` package is protected

* Updates `poetry` to `1.0`

### 0.11.0[¶](#id33 "Permalink to this heading")

#### Features[¶](#id34 "Permalink to this heading")

* **Breaking**: now `pipe()` does not require argument to be the first value,

instead it is required to use: `pipe(f1, f2, f3, f4)(value)`

* **Breaking**: dropped everything from `returns/\_\_init\_\_.py`,

because we now have quite a lot of stuff

* **Breaking**: dropped support of zero argument functions for `Nothing.fix`

* **Breaking**: dropped support of zero argument functions for `Nothing.rescue`

* `Maybe` now has `.failure()` to match the same API as `Result`

* Adds `identity` function

* Adds `tap` function

* Now `pipe` allows to pipe 8 steps

* Adds `coalesce\_result` and `coalesce\_maybe` converters

#### Bugfixes[¶](#id35 "Permalink to this heading")

* Fixes that code inside `.fix` and `.rescue` of `Maybe` might be called twice

#### Misc[¶](#id36 "Permalink to this heading")

* Now all methods have doctests

* Updates docs about `Success` and `\_Success`, `Failure` and `\_Failure`

* Updates docs about `@pipeline`

* Typechecks async functions and decorators inside `typesafety/` tests

### 0.10.0[¶](#id37 "Permalink to this heading")

#### Features[¶](#id38 "Permalink to this heading")

* **Breaking**: `python>=3.7,<=3.7.2` are not supported anymore,

because of a bug inside `typing` module

* **Breaking**: Now `bind` does not change the type of an error

* **Breaking**: Now `rescue` does not change the type of a value

* **Breaking**: Renames `map\_failure` to `alt`

* Adds `box()` function with the ability

to box function for direct container composition like:

`a -> Container[b]` to `Container[a] -> Container[b]`

* Adds `IO.lift()` function to lift `a -> a` to `IO[a] -> IO[a]`

* Adds `pipe()` function to `pipeline.py`

* Adds `\_\_hash\_\_()` magic methods to all containers

#### Bugfixes[¶](#id39 "Permalink to this heading")

* Changes `Any` to `NoReturn` in `Success` and `Failure`

* Now all type parameters in `Result`, `Maybe`, and `IO` are covariant

#### Misc[¶](#id40 "Permalink to this heading")

* Massive docs rewrite

* Updates `mypy` version

* Updates `wemake-python-styleguide` and introduces `nitpick`

* Updates `pytest-plugin-mypy`, all tests now use `yml`

### 0.9.0[¶](#id41 "Permalink to this heading")

#### Features[¶](#id42 "Permalink to this heading")

* Provides a bunch of primitive interfaces to write your own containers

* Adds `.map\_failure()` method

* Adds `flatten()` function to join nested containers

#### Bugfixes[¶](#id43 "Permalink to this heading")

* Fixes type of `Maybe.fix` and `Maybe.rescue` to work with both `lambda: 1` and `lambda \_: 1`

#### Misc[¶](#id44 "Permalink to this heading")

* Improves `README`

### 0.8.0[¶](#id45 "Permalink to this heading")

#### Features[¶](#id46 "Permalink to this heading")

* Reintroduces the `Maybe` container, typed!

* Introduces converters from one type to another

* Adds `mypy` plugin to type decorators

* Complete rewrite of `Result` types

* Partial API change, now `Success` and `Failure` are not types, but functions

* New internal types introduced: `FixableContainer` and `ValueUnwrapContainer`

#### Bugfixes[¶](#id47 "Permalink to this heading")

* Fixes issue when you could return `IO` container from `Result.bind`

* Fixes `@pipeline` return type

#### Misc[¶](#id48 "Permalink to this heading")

* Reapplied all types to `.py` files

* Improved docs about `IO` and `Container` concept

* Adds docs about container composition

* Moves from `Alpha` to `Beta`

### 0.7.0[¶](#id49 "Permalink to this heading")

#### Features[¶](#id50 "Permalink to this heading")

* Adds `IO` container

* Adds `unsafe` module with unsafe functions

* Changes how functions are located inside the project

#### Bugfixes[¶](#id51 "Permalink to this heading")

* Fixes container type in `@pipeline`

* Now `is\_successful` is public

* Now `raise\_exception` is public

#### Misc[¶](#id52 "Permalink to this heading")

* Changes how `str()` function works for container types

* Total rename to “container” in the source code

### Version 0.6.0[¶](#version-0-6-0 "Permalink to this heading")

#### Features[¶](#id53 "Permalink to this heading")

* `safe` and `pipeline` now supports `asyncio`

* `is\_successful` now returns `Literal` types if possible

### Version 0.5.0[¶](#version-0-5-0 "Permalink to this heading")

#### Features[¶](#id54 "Permalink to this heading")

* Adds `compose` helper function

* Adds public API to `import returns`

* Adds `raise\_exception` helper function

* Adds full traceback to `.unwrap()`

#### Misc[¶](#id55 "Permalink to this heading")

* Updates multiple dev-dependencies, including `mypy`

* Now search in the docs is working again

* Relicenses this project to `BSD`

* Fixes copyright notice in the docs

### Version 0.4.0 aka Goodbye, containers![¶](#version-0-4-0-aka-goodbye-containers "Permalink to this heading")

#### Features[¶](#id56 "Permalink to this heading")

* Moves all types to `.pyi` files

* Renames all classes according to new naming pattern

* **HUGE** improvement of types

* Renames `fmap` to `map`

* Renames `do\_notation` to `pipeline`, moves it to `functions.py`

* Renames `ebind` to `rescue`

* Renames `efmap` to `fix`

* Renames `container` to `Container`

* Removes `Maybe` container, since typing does not have `NonNullable` type

### Version 0.3.1[¶](#version-0-3-1 "Permalink to this heading")

#### Bugfixes[¶](#id57 "Permalink to this heading")

* Adds `py.typed` file to be `PEP561` compatible

### Version 0.3.0, Renamed to `returns`[¶](#version-0-3-0-renamed-to-returns "Permalink to this heading")

The project is renamed to `returns` and moved to `dry-python` org.

#### Features[¶](#id58 "Permalink to this heading")

* Adds `.pyi` files for all modules,

to enable `mypy` support for 3rd party users

### Version 0.2.0[¶](#version-0-2-0 "Permalink to this heading")

#### Features[¶](#id59 "Permalink to this heading")

* Adds `Maybe` container

* Adds immutability and `\_\_slots\_\_` to all containers

* Adds methods to work with failures

* Adds `safe` decorator to convert exceptions to `Result` container

* Adds `is\_successful()` function to detect if your result is a success

* Adds `failure()` method to unwrap values from failed containers

#### Bugfixes[¶](#id60 "Permalink to this heading")

* Changes the type of `.bind` method for `Success` container

* Changes how equality works, so now `Failure(1) != Success(1)`

* Changes how new instances created on unused methods

#### Misc[¶](#id61 "Permalink to this heading")

* Improves docs

### Version 0.1.1[¶](#version-0-1-1 "Permalink to this heading")

#### Bugfixes[¶](#id62 "Permalink to this heading")

* Changes how `PyPI` renders package’s page

#### Misc[¶](#id63 "Permalink to this heading")

* Improves `README` with new badges and installation steps

### Version 0.1.0[¶](#version-0-1-0 "Permalink to this heading")

Initial release. Featuring only `Result` and `do\_notation`.

Indices and tables[¶](#indices-and-tables "Permalink to this heading")

======================================================================

* [Index](genindex.html)

* [Module Index](py-modindex.html)

* [Search Page](search.html)

