ekampf / pymaybe

A Python implementation of the Maybe pattern
BSD 3-Clause "New" or "Revised" License
208 stars 6 forks source link

Typehints #11

Open ramarivera opened 1 year ago

ramarivera commented 1 year ago

Hey, just stumbled on this library when a friend recommended it to me.

I like the syntax sugar, but I noticed it doesn't provide typehints, so the code I would save with this I need to spend doing cast .

Is that by design / for a particular reason? If not, would you accept a PR adding them?

LEv145 commented 1 year ago

I think the problem is in the value argument of the maybe function https://github.com/ekampf/pymaybe/blob/master/pymaybe/__init__.py#L569-L570

Typing linters don't understand isinstance, so they warn about a possible error:

>>> maybe(Maybe()).log
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Maybe' object has no attribute 'log'

image

Сan use @overload to fix it: https://docs.python.org/3/library/typing.html#typing.overload

@overload
def maybe(value: Maybe) -> Maybe:   # But such code can also be broken if `Maybe` is a child element of object
    ...  
@overload
def maybe(value: None) -> Nothing:
    ...
@overload
def maybe(value) -> Something:
    ...

Therefore, it is more logical to remove these lines or make a function without them:

if isinstance(value, Maybe):
    return value