【发布时间】:2017-11-28 02:46:44
【问题描述】:
我正在使用 Python 3.6.1、mypy 和打字模块。我创建了两个自定义类型,Foo 和 Bar,然后在我从函数返回的字典中使用它们。 dict 被描述为将str 映射到Foo 和Bar 的Union。然后我想在一个函数中使用这个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()
我尝试按原样使用这些值:
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 转换为其子类型之一?
【问题讨论】:
标签: python python-3.x type-hinting mypy