Maybe

The Maybe container is used when a series of computations could return None at any point.

Maybe container

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

>>> str(Maybe.from_value(1))
'<Some: 1>'

>>> str(Maybe.from_value(None))
'<Nothing>'

Usage

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

>>> @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_value(order.user).map(
...         lambda user: user.address,
...     ).map(
...         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>'

>>> str(get_street_address(empty_user))
'<Nothing>'
>>> str(get_street_address(empty_address))
'<Nothing>'
>>> str(get_street_address(empty_street))
'<Nothing>'

Optional type

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.

Decorators

Limitations

Typing will only work correctly if our mypy plugin is used. This happens due to mypy issue.

maybe

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

>>> @maybe
... def number(num: int) -> Optional[int]:
...     if num > 0:
...         return num
...     return None

>>> result: Maybe[int] = number(1)
>>> str(result)
'<Some: 1>'

FAQ

How can I turn Maybe into Optional again?

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_value(1).value_or(None) == 1
>>> assert Maybe.from_value(None).value_or(None) is 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?

Let’s say you have this dict: {'a': 1, 'b': None} And you want to get Maybe[int] values by string keys from there. When trying both existing key 'b' and missing key 'c' you will end up with Nothing for both values.

But, they are different! You might need to know exactly which case you are dealing with.

In this case, it is better to switch to Result type. Let’s see how to model this real-life situation:

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

>>> source = {'a': 1, 'b': None}
>>> md = safe(lambda key: source[key])

>>> assert md('a') == Success(1)
>>> assert md('b') == Success(None)

>>> # Is: Failure(KeyError('c'))
>>> assert md('c').failure().args == ('c',)

This way you can tell the difference between empty values (None) and missing keys.

You can always use returns.converters.result_to_maybe() to convert Result to Maybe.

See the original issue about Some(None) for more details and the full history.

Why there’s no IOMaybe?

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.

Why Maybe does not have rescue, fix, and alt methods?

Well, because Maybe only has a single type argument: _ValueType. And all these method implies that we also has _ErrorType.

We used to have them. There were several issues:

  1. If we leave their signature untouched (with the explicit None error type) then we would have to write functions that always ignore the passed argument. It is a bit ugly!

  2. If we change the signature of the passed function to have zero arguments, then we would have a lot of problems with typing. Because now different types would require different callback functions for the same methods!

We didn’t like both options and dropped these methods in some early release.

Now, Maybe has 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.

API Reference

graph TD; _Nothing _Some Maybe BaseContainer --> Maybe Generic --> Maybe Maybe --> _Nothing Maybe --> _Some
class Maybe(inner_value)[source]

Bases: returns.primitives.container.BaseContainer, typing.Generic

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.

success_type

Success type that is used to represent the successful computation.

Parameters

inner_value (+_ValueType) –

alias of _Some

failure_type

Failure type that is used to represent the failed computation.

Parameters

inner_value (None) –

alias of _Nothing

map(function)[source]

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[[+_ValueType], Optional[~_NewValueType]]) –

Return type

Maybe[~_NewValueType]

apply(function)[source]

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 (Maybe[Callable[[+_ValueType], ~_NewValueType]]) –

Return type

Maybe[~_NewValueType]

bind(function)[source]

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[[+_ValueType], Maybe[~_NewValueType]]) –

Return type

Maybe[~_NewValueType]

value_or(default_value)[source]

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 (~_NewValueType) –

Return type

Union[+_ValueType, ~_NewValueType]

or_else_call(function)[source]

Get value from successful container or default value from failed one.

Really close to value_or() but works with lazy values. This method is unique to Maybe container, because other containers do have .rescue, .alt, .fix methods. But, Maybe does not.

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[[], ~_NewValueType]) –

Return type

Union[+_ValueType, ~_NewValueType]

unwrap()[source]

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

+_ValueType

failure()[source]

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]

Creates new instance of Maybe container based on a value.

>>> from returns.maybe import Maybe, Some, Nothing
>>> assert Maybe.from_value(1) == Some(1)
>>> assert Maybe.from_value(None) == Nothing
Parameters

inner_value (Optional[+_ValueType]) –

Return type

Maybe[+_ValueType]

classmethod from_iterable(inner_value)[source]

Transforms an iterable of Maybe containers into a single container.

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

>>> assert Maybe.from_iterable([
...    Some(1),
...    Some(2),
... ]) == Some((1, 2))

>>> assert Maybe.from_iterable([
...     Some(1),
...     Nothing,
... ]) == Nothing

>>> assert Maybe.from_iterable([
...     Nothing,
...     Some(1),
... ]) == Nothing
Parameters

inner_value (Iterable[Maybe[+_ValueType]]) –

Return type

Maybe[Sequence[+_ValueType]]

Some(inner_value)[source]

Public unit function of protected _Some type.

Can return Nothing for passed None argument. Because Some(None) does not make sence.

>>> from returns.maybe import Some
>>> str(Some(1))
'<Some: 1>'
>>> str(Some(None))
'<Nothing>'
Parameters

inner_value (Optional[+_ValueType]) –

Return type

Maybe[+_ValueType]

Nothing: returns.maybe.Maybe[NoReturn] = <returns.maybe._Nothing object>

Public unit value of protected _Nothing type.

maybe(function)[source]

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)

Requires our mypy plugin.

Parameters

function (Callable[…, Optional[+_ValueType]]) –

Return type

Callable[…, Maybe[+_ValueType]]