Skip to content

Instantly share code, notes, and snippets.

@Kwpolska
Last active June 24, 2017 19: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 Kwpolska/896312ba50dde05f8787cc83e17e582b to your computer and use it in GitHub Desktop.
Save Kwpolska/896312ba50dde05f8787cc83e17e582b to your computer and use it in GitHub Desktop.
from typing import Dict, Union, NewType
Foo = NewType("Foo", str)
Bar = NewType("Bar", int)
def get_data() -> Dict[str, Union[Foo, Bar]]:
return {"foo": Foo("one"), "bar": Bar(2)}
def process(foo_value: Foo, bar_value: Bar) -> None:
pass
d = get_data()
process(d["foo"], d["bar"])
# typing-union.py:15: error: Argument 1 to "process" has incompatible type "Union[Foo, Bar]"; expected "Foo"
# typing-union.py:15: error: Argument 2 to "process" has incompatible type "Union[Foo, Bar]"; expected "Bar"
process(Foo(d["foo"]), Bar(d["bar"]))
# typing-union.py:20: error: Argument 1 to "Foo" has incompatible type "Union[Foo, Bar]"; expected "str"
# typing-union.py:20: error: Argument 1 to "Bar" has incompatible type "Union[Foo, Bar]"; expected "int"
## ANSWERED HERE: https://stackoverflow.com/a/44739888/712267
from typing import cast
process(cast(Foo, d["foo"]), cast(Bar, d["bar"]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment