ITADN

Feature request: add bool conversion to `Maybe`

#2177ClosedInAnYan 创建于 2025-06-24
I
InAnYancommented
Refs: <https://github.com/dry-python/returns/issues/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: ```python 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: ```python 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 (<https://github.com/dry-python/returns/issues/874#issuecomment-805555193>): > 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>): ```plain 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)`.
关闭于 2025-06-27 5 条评论