Last active
October 29, 2016 00:19
-
-
Save TheDan64/69f7f9ac220e15f6b2bfdf36f93fdeda to your computer and use it in GitHub Desktop.
Would like to get this to work with MyPy
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 | |
L = TypeVar('L') | |
R = TypeVar('R') | |
class Either(Generic[L, R]): | |
pass | |
class Left: | |
def __init__(self, value): | |
self.value = value | |
def is_left(self) -> bool: | |
return True | |
def is_right(self) -> bool: | |
return False | |
class Right: | |
def __init__(self, value): | |
self.value = value | |
def is_left(self) -> bool: | |
return False | |
def is_right(self) -> bool: | |
return True | |
def either_or() -> Either[int, str]: | |
""" Some fn that returns one of two types of data. | |
Would like MyPy to say this is a valid return type if | |
and only if the inner type matches. | |
Example: | |
return Left(10) # ok | |
return Right("string") # ok | |
return Left("string") # invalid | |
return Right(10) # invalid | |
return "string" # invalid | |
""" | |
return Right("Hello!") | |
if __name__ == "__main__": | |
unknown = either_or() | |
if unknown.is_right(): | |
print("Found a string: {}".format(unknown.value)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment