![](https://secure.gravatar.com/avatar/fa430c81cf0a937c468a543ef0115f21.jpg?s=120&d=mm&r=g)
Potentially off topic for this list. But posting here to get suggestions on where I might find the right audience for the discussion. Problem: how to transpile python code that might throw exceptions to languages that don't have exceptions, but do have Result<T, Err>. Does something like this make sense? ``` from typing import Optional, Generic, TypeVar from dataclasses import dataclass T = TypeVar("T") @dataclass class Result(Generic[T]): data: T error: Optional[Exception] ``` Details: https://github.com/adsharma/py2many/issues/322 -Arun
![](https://secure.gravatar.com/avatar/16090471dbf2942bf4c002ac1ee0cbc7.jpg?s=120&d=mm&r=g)
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 ```
![](https://secure.gravatar.com/avatar/5dc484e83f87a994a4c21c21e8b9c1b0.jpg?s=120&d=mm&r=g)
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
participants (3)
-
Arun Sharma
-
Joseph Perez
-
Никита Соболев