Created
April 5, 2021 20:16
-
-
Save pawelrubin/374b841285ab55c5b73f7287ca31c3b4 to your computer and use it in GitHub Desktop.
Either type in Python
This file contains 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
from typing import Generic, TypeVar | |
VT = TypeVar("VT") | |
ET = TypeVar("ET") | |
class Matchable: | |
__match_args__ = ("__match_self_prop__",) | |
@property | |
def __match_self_prop__(self): | |
return self | |
class Left(Matchable, Generic[ET]): | |
def __init__(self, error: ET) -> None: | |
self.error = error | |
def __str__(self) -> str: | |
return str(self.error) | |
class Right(Matchable, Generic[VT]): | |
def __init__(self, value: VT) -> None: | |
self.value = value | |
def __str__(self) -> str: | |
return str(self.value) | |
Either = Left[ET] | Right[VT] | |
def calculate_ok() -> Either[str, int]: | |
return Right(42) | |
def calculate_bad() -> Either[str, int]: | |
return Left("Oops, error!") | |
x = calculate_ok() | |
y = calculate_bad() | |
for el in [x, y]: | |
match el: | |
case Right(n): | |
print(n) | |
case Left(err): | |
print(err) | |
# 42 | |
# Oops, error! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment