Skip to content

Instantly share code, notes, and snippets.

@pawelrubin
Created April 5, 2021 20:16
Show Gist options
  • Save pawelrubin/374b841285ab55c5b73f7287ca31c3b4 to your computer and use it in GitHub Desktop.
Save pawelrubin/374b841285ab55c5b73f7287ca31c3b4 to your computer and use it in GitHub Desktop.
Either type in Python
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