Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_maybe_decorater(self):
maybe_int = maybe(int)
assert maybe_int('1') == Just(1)
assert maybe_int('whoops') == Nothing()
def maybes(value_strategy=anything()):
justs = builds(maybe.Just, value_strategy)
nothings = just(maybe.Nothing())
return one_of(justs, nothings)
def _test_nothing_identity_law(self):
assert Nothing().map(identity) == Nothing()
def _test_nothing_equality(self):
assert Nothing() == Nothing()
def test_nothing() -> Maybe[Any]:
return Nothing().map(identity)
def test_nothing() -> Maybe[str]:
return Nothing().map(lambda a: a.lower())
return isinstance(other, Nothing)
def __repr__(self) -> str:
return 'Nothing()'
def or_else(self, default: B) -> Union[A, B]:
return default
def map(self, f: Callable[[Any], B]) -> 'Maybe[B]':
return self
def __bool__(self) -> bool:
return False
Maybe = Union[Nothing, Just[A]]
"""
Type-alias for `Union[Nothing, Just[TypeVar('A')]]`
"""
Maybe.__module__ = __name__
def maybe(f: Callable[..., B]) -> Callable[..., Maybe[B]]:
"""
Wrap a function that may raise an exception with a `Maybe`.
Can also be used as a decorator. Useful for turning
any function into a monadic function
Example:
>>> to_int = maybe(int)
>>> to_int("1")
Just(1)
>>> from pfun.either import Left, Right, Either
>>> def f(i: str) -> Maybe[Either[int, str]]:
... if i == 0:
... return Just(Right('Done'))
... return Just(Left(i - 1))
>>> tail_rec(f, 5000)
Just('Done')
Args:
f: function to run "recursively"
a: initial argument to `f`
Return:
result of `f`
"""
maybe = f(a)
if isinstance(maybe, Nothing):
return maybe
either = maybe.get
while isinstance(either, Left):
maybe = f(either.get)
if isinstance(maybe, Nothing):
return maybe
either = maybe.get
return Just(either.get)
"""
Return a possible None value to `Maybe`
Example:
>>> from_optional('value')
Just('value')
>>> from_optional(None)
Nothing()
Args:
optional: optional value to convert to `Maybe`
Return:
`Just(optional)` if `optional` is not `None`, `Nothing` otherwise
"""
if optional is None:
return Nothing()
return Just(optional)