Created
August 25, 2022 08:51
-
-
Save IgorZyktin/5825f65fec3701c08b6b1a134f44245d to your computer and use it in GitHub Desktop.
Type safe returns
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
from typing import Generic | |
from typing import TypeVar | |
from typing_extensions import reveal_type | |
V = TypeVar('V', covariant=True) | |
E = TypeVar('E', covariant=True) | |
class Success(Generic[V]): | |
def __init__(self, value: V): | |
self.value = value | |
class Failure(Generic[E]): | |
def __init__(self, error: E): | |
self.error = error | |
Result = Success[V] | Failure[E] | |
def some_func(number: int) -> Result[int, str]: | |
value = random.randint(0, number) | |
if value == number: | |
return Failure('no luck') | |
return Success(value) | |
def do_stuff() -> None: | |
for i in range(5): | |
result = some_func(i) | |
reveal_type(result) | |
# Revealed type is "Union[Success[int], Failure[str]]" | |
if isinstance(result, Failure): | |
reveal_type(result) | |
# Revealed type is "Failure[str]" | |
print(f'{i} => failure, {result.error}') | |
else: | |
reveal_type(result) | |
# Revealed type is "Success[int]" | |
print(f'{i} => success, {result.value}') | |
if __name__ == '__main__': | |
do_stuff() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment