51 lines
1.1 KiB
Python
51 lines
1.1 KiB
Python
from typing import Generic, TypeVar
|
|
|
|
class UnwrapException(Exception):
|
|
def __init__(self, *args: object) -> None:
|
|
super().__init__(*args)
|
|
|
|
T = TypeVar("T")
|
|
E = TypeVar("E")
|
|
|
|
class Result(Generic[T, E]):
|
|
def __init__(self) -> None:
|
|
super().__init__()
|
|
|
|
def ok(self) -> bool:
|
|
raise NotImplementedError()
|
|
|
|
def value(self) -> T:
|
|
raise NotImplementedError()
|
|
|
|
def error(self) -> E:
|
|
raise NotImplementedError()
|
|
|
|
class Ok(Result[T, E]):
|
|
def __init__(self, value: T) -> None:
|
|
super().__init__()
|
|
self.__value = value
|
|
|
|
def ok(self) -> bool:
|
|
return True
|
|
|
|
def value(self) -> T:
|
|
return self.__value
|
|
|
|
def error(self) -> E:
|
|
raise UnwrapException("cannot unwrap error of ok result")
|
|
|
|
class Err(Result[T, E]):
|
|
def __init__(self, error: E) -> None:
|
|
super().__init__()
|
|
self.__error = error
|
|
|
|
def ok(self) -> bool:
|
|
return False
|
|
|
|
def value(self) -> T:
|
|
raise UnwrapException("cannot unwrap value of error result")
|
|
|
|
def error(self) -> E:
|
|
return self.__error
|
|
|