def test_match_err(): msg = 'Nopop' return_err = Match(Err('Err')) \ .err(err_op, msg) \ .collect() assert return_err == err_op(msg)
def test_match_ok(): msg = 'Okdok' return_ok = Match(Ok('Success')) \ .ok(ok_op, msg) \ .collect() assert return_ok == ok_op(msg)
def authenticate(username, password): if username == 'ok' and password == 'err': user = User(username) return Ok(user) return Err("You're not allowed here!") def awesome_authenticated_stuff(user: User) -> User: return user def awful_result(msg: str): return msg if __name__ == '__main__': username = input('username: '******'password: ') result = authenticate(username, password) collected_value = Match(result) \ .ok(awesome_authenticated_stuff, result.value) \ .err(awful_result, result.value) \ .collect() print(collected_value)
from okerr import Err, Ok, Match def divide(a, b): try: return Ok(a / b) except ZeroDivisionError: return Err('Oh no, a ZeroDivisionError just happened') if __name__ == '__main__': first_number = int(input('Please, inform an integer \n')) second_number = int(input('Please, inform another integer \n')) result = divide(first_number, second_number) Match(result) \ .ok(lambda: print(result.value)) \ .err(lambda: print(result.value))
def test_match_return_none_with_no_op(): return_ok = Match(Ok('Success')) \ .ok(None) \ .collect() assert return_ok is None
def test_match_ok_with_kwargs(): return_ok = Match(Ok('Success')) \ .ok(op_with_kwargs, a=1, b=2, c=3, d=4, e=5) \ .collect() assert return_ok == op_with_kwargs()
def test_match_ok_with_args(): return_ok = Match(Ok('Success')) \ .ok(op_with_args, 1, 2, 3, 4, 5) \ .collect() assert return_ok == op_with_args()
def test_match_ok_without_arg(): return_ok = Match(Ok('Success')) \ .ok(op_without_arg) \ .collect() assert return_ok == op_without_arg()