我正在使用 Python 3.6.1、mypy 和打字模块。我创建了两个自定义类型,Foo
和Bar
,然后在我从函数返回的字典中使用它们。dict 被描述为映射到str
aUnion
和。然后我想在一个函数中使用这个dict中的值,每个函数只命名一个参数:Foo
Bar
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"
如何将Union
其转换为其子类型之一?