gpt4 book ai didi

python - 如何在 Python 中将 typing.Union 转换为其子类型之一?

转载 作者:太空狗 更新时间:2023-10-30 01:05:24 25 4
gpt4 key购买 nike

我正在使用 Python 3.6.1、mypy 和 typing 模块。我创建了两个自定义类型,FooBar,然后在我从函数返回的字典中使用它们。字典被描述为将 str 映射到 FooBarUnion。然后我想在一个函数中使用这个字典中的值,每个函数只命名一个参数:

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 转换为其子类型之一?

最佳答案

你必须使用 cast() :

process(cast(Foo, d["foo"]), cast(Bar, d["bar"]))

来自 PEP 484 的 Casts 部分:

Occasionally the type checker may need a different kind of hint: the programmer may know that an expression is of a more constrained type than a type checker may be able to infer.

没有办法拼写特定类型的值与字典键的特定值。您可能需要考虑返回 named tuple相反,可以按键输入:

from typing import Dict, Union, NewType, NamedTuple

Foo = NewType("Foo", str)
Bar = NewType("Bar", int)

class FooBarData(NamedTuple):
foo: Foo
bar: Bar

def get_data() -> FooBarData:
return FooBarData(foo=Foo("one"), bar=Bar(2))

现在类型提示器确切地知道每个属性类型是什么:

d = get_data()
process(d.foo, d.bar)

或者您可以使用 dataclass :

from dataclasses import dataclass

@dataclass
class FooBarData:
foo: Foo
bar: Bar

这使得添加可选属性以及控制其他行为(例如相等性测试或排序)变得更加容易。

我更喜欢 typing.TypedDict ,这更适合与遗留代码库和 (JSON) 序列化一起使用。

关于python - 如何在 Python 中将 typing.Union 转换为其子类型之一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44739764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com