Python version of Rust Result Sum Type
I try to implement a Python version of the Result<T, E> sum type in rust which can be used with match/case pattern matching.
The pattern matching with sub-patterns like case Err(e) could be implemented in Python with the __match_args__ dunder attribute. This is how Result[T, E], OK() and Err() defined:
1import typing
2
3T = typing.TypeVar('T')
4E = typing.TypeVar('E')
5
6class Result[T, E]:
7 __match_args__ = ('_val',)
8 def __init__(self, val):
9 self._val = val
10
11class Ok[T](Result[T, ...]):
12 pass
13
14class Err[E](Result[..., E]):
15 pass
Below is the match/case block, note that if you have different types value to match(like different Error types), the guard(if statement behind the case pattern) must be used.
1>>> def match(value):
2... match value:
3... case Ok(v): print(v)
4... case Err(e) if type(e) is str: print('str', e)
5... case Err(e) if type(e) is int: print('int', e)
6...
7>>> ok_result = Ok('Hello World')
8... e1 = Err('incorrect value')
9... e2 = Err(404)
10...
11>>> match(ok_result)
12Hello World
13>>> match(e1)
14str incorrect value
15>>> match(e2)
16int 404