我正在使用Python 3.6.1,mypy和打字模块。我创建了两个自定义类型Foo和Bar,然后在从函数返回的字典中使用了它们。该字典被描述为映射str到Union的Foo和Bar。然后,我想在每个仅命名一个参数的函数中使用此dict中的值:
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()
Run Code Online (Sandbox Code Playgroud)
我尝试按原样使用值:
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 …Run Code Online (Sandbox Code Playgroud)