Last active
June 24, 2017 19:26
-
-
Save Kwpolska/896312ba50dde05f8787cc83e17e582b 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 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