Skip to content

Instantly share code, notes, and snippets.

@Michael0x2a
Created July 10, 2017 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Michael0x2a/1bf3a88baba1bc8fd8d3c02253b3d701 to your computer and use it in GitHub Desktop.
Save Michael0x2a/1bf3a88baba1bc8fd8d3c02253b3d701 to your computer and use it in GitHub Desktop.
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