Created
July 10, 2017 21:26
-
-
Save Michael0x2a/1bf3a88baba1bc8fd8d3c02253b3d701 to your computer and use it in GitHub Desktop.
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
from typing import overload, Sequence, Union, NewType | |
from mypy_extensions import NoReturn | |
# by convention, underlying type should not be 'str' | |
ArgList = NewType('ArgList', Sequence[str]) | |
@overload | |
def make_arglist(x: str) -> NoReturn: ... | |
@overload | |
def make_arglist(x: Sequence[str]) -> ArgList: ... | |
def make_arglist(x: Sequence[str]) -> Union[ArgList, None]: | |
# Or maybe even omit the check altogether to minimize runtime cost, since | |
# the typechecker ought to be able to do this check for us | |
if isinstance(x, str): | |
raise Exception() | |
else: | |
return ArgList(x) | |
def bar(x: ArgList) -> str: | |
return " ".join(x) | |
def main() -> None: | |
# I want this to typecheck when using lists, tuples, custom sequences... | |
x = make_arglist(["hello", "world"]) | |
print(bar(x)) | |
# But want this to fail noisily | |
# (mypy currently silently stops typechecking instead) | |
y = make_arglist("hello") | |
print(bar(y)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment