Skip to content

Feature request: add bool conversion to Maybe #2177

@InAnYan

Description

@InAnYan

Refs: #874.

Currently, Maybe type doesn't have special methods for being treated as bools, so any Maybe object is True in Python.

However, I find that it doesn't fit well in Python idioms. One cool feature of Optional in Python is that I can do statements like this:

if await self.find_model(id):
    <do something>
...

So I can easily check if the value is truthy or falsey. I don't need to write not is None.

However, if self.find_model would return a Maybe type, then code becomes more complex:

if (await self.find_model(id)) != Nothing:
    <do something>
...

I believe it would be a good addition to Maybe to add __bool__ method.

Couple of remarks:

  1. I'm aware that checking whether the object is None and falsiness of a value in Python are different things. Any Python developer should be aware of this. And if anyone would return a list or strings in find_model, then that person wouldn't really be using Optional or Maybe, I think.
  2. One of the maintainer raised a question in other issue (Request: Truthiness of Result, Correct way to filter over Iterable[Result] #874 (comment)):

It is not clear what we check with bool(), the container itself? Or its content? In other words: Success(False) is True or False?

In my opinion, it's crystal clear. If I analyze a Maybe object then I analyze Maybe object, not it's value. It aligns with the documentation as well (https://returns.readthedocs.io/en/latest/pages/maybe.html#how-to-model-absence-of-value-vs-presence-of-none-value):

 So, the first thing to remember is that:

>>> assert Some(None) != Nothing

I have one more positive argument to this semantic decision: imagine one would like to model these kinds of value:

  1. Undefined (not supplied, not present).
  2. None (present, but null).
  3. Present.

This could be easily modeled if __bool__ would check whether a Maybe is Nothing or Something:

  1. Undefined - Nothing.
  2. None - Something(None).
  3. Present - Something(123).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions