Consider `Maybe` methods that state if a value is present/absent
See original GitHub issueHi,
I’m just getting my feet wet with returns
. As a first iteration, I’m trying to introduce Maybe
into a somewhat larger codebase of mine.
One thing that irks me a bit is code like this:
Coming from code like this:
item: Optional[Item] = find_item(item_id)
if item is None:
raise SomeCustomException("ohai")
(Naively) porting to Maybe
leaves me with this:
item: Maybe[Item] = find_item(item_id).value_or(None)
if item is None:
raise SomeCustomException("ohai")
While I can replace is not None
checks after which I want to process the value with Maybe.map
(and not raise an exception if the value is missing) and gain more succinct code, almost the opposite seems to be the case if I don’t want to work with the potential value but rather its existence itself.
Another example:
# traditional
token: Optional[Token] = find_token(some_key)
valid_token_found: bool = (token is not None) and not token.is_expired
# `returns`-y way
from returns.maybe import Some
token: Maybe[Token] = find_token(some_key)
valid_token_found: bool = token.map(lambda t: not t.is_expired) is Some
What I’m looking for is a method like [is_]{present, absent, some, none}
, has_value
, empty
, etc. to allow me to do this:
# `returns`-y way
# NB: No import necessary!
token: Maybe[Token] = find_token(some_key)
valid_token_found: bool = token.map(lambda t: not t.is_expired).present
Am I overlooking some best practice that avoids imports and identity/equality operators? If not, are you open to consider adding such (potentially even more auto-complete-friendly) methods?
Thanks!
Issue Analytics
- State:
- Created 4 years ago
- Comments:11 (11 by maintainers)
Top GitHub Comments
Hi @sobolevn, thank you for your quick response.
My intent is not to override
is
for this use case.While
is_successful
technically works, I see a few downsides:From my experience with introducing
Optional
(both Guava’s and Java 8’s) into multiple rather big Java code bases I’ve learned that acceptance with people is higher if they don’t have to figure out too much. Pressing the auto-complete hotkey usually worked well; but having them to know to import something, and what exactly, and to do actually that would be a burden resulting in animosity towards the introduction of such a data structure and concept, and developers trying to introduce it 😃I’m not requesting something super special here, but rather something I’m familiar with from other environments. For example:
Maybe
hasisJust
andisNothing
Optional
hasisPresent
(but no counter-part; discussion)Optional
hasisPresent
and (as of Java 11)isEmpty
Option
hasisDefined
andisEmpty
Option
hasis_some
andis_none
or_else_call
sounds great! 👍