gpt4 book ai didi

python - 如何使用字典和 google protobuf 枚举的类型提示?

转载 作者:行者123 更新时间:2023-12-03 23:08:49 29 4
gpt4 key购买 nike

我正在尝试使用 protobuf 枚举作为字典中值的类型,但由于某种原因它不起作用。

我在 proto 中的枚举定义是:

enum Device {
UNSPECIFIED = 0;
ON = 1;
OFF = 2;
}

编译导入成功后,出现如下代码报错。
from devices_pb2 import Device

def foo(device: Device) -> Dict[str, Device]:
pass

错误信息:
    def foo(device: Device) -> Dict[str, Device]:
File "/home/ivan/anaconda3/envs/py37/lib/python3.7/typing.py", line 254, in inner
return func(*args, **kwds)
File "/home/ivan/anaconda3/envs/py37/lib/python3.7/typing.py", line 629, in __getitem__
params = tuple(_type_check(p, msg) for p in params)
File "/home/ivan/anaconda3/envs/py37/lib/python3.7/typing.py", line 629, in <genexpr>
params = tuple(_type_check(p, msg) for p in params)
File "/home/ivan/anaconda3/envs/py37/lib/python3.7/typing.py", line 142, in _type_check
raise TypeError(f"{msg} Got {arg!r:.100}.")
TypeError: Parameters to generic types must be types. Got <google.protobuf.internal.enum_type_wrapper.EnumTypeWrapper object at 0x7f4df6d81850>.

但是,如果我不使用字典,那么它就可以正常工作:
def foo(device: Device) -> Device:
pass

我想知道是否有解决此问题的方法?

最佳答案

添加以下内容解决了问题:

from __future__ import annotations

有关更多详细信息,请检查 here

关于python - 如何使用字典和 google protobuf 枚举的类型提示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60342896/

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