We took this approach: https://github.com/dry-python/returns/blob/master/returns/result.py вт, 22 июн. 2021 г. в 11:02, Joseph Perez <joperez@hotmail.fr>:
Rust `Result<T, E>` is an algebraic data type. Python doesn't have equivalent builtin construct, but it can simply be emulated using union and dataclasses. For example:
```python from typing import TypeVar from dataclasses import dataclass
@dataclass class Ok(Generic[T]): value: T
@dataclass class Err(Generic[E]): error: E
Result = Ok[T] | Err[E] ```
It does play well with pattern matching:
```python def unwrap(result: Result[T, E]) -> T: match result: case Ok(v): return v case Err(e): raise e if isinstance(e, Exception) else Exception(e)
def ok(result: Result[T, E]) -> T | None: match result: case Ok(v): if v is None: warnings.warn("ok was called with a None result", RuntimeWarning) return v case _: return None
… # all Result methods can be implemented like that ``` _______________________________________________ Typing-sig mailing list -- typing-sig@python.org To unsubscribe send an email to typing-sig-leave@python.org https://mail.python.org/mailman3/lists/typing-sig.python.org/ Member address: n.a.sobolev@gmail.com