小编Chr*_*ick的帖子

如何在Python中将type.union强制转换为其子类型之一?

我正在使用Python 3.6.1,mypy和打字模块。我创建了两个自定义类型FooBar,然后在从函数返回的字典中使用了它们。该字典被描述为映射strUnionFooBar。然后,我想在每个仅命名一个参数的函数中使用此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)

python type-hinting python-3.x mypy

5
推荐指数
1
解决办法
1233
查看次数

标签 统计

mypy ×1

python ×1

python-3.x ×1

type-hinting ×1