如何在字典和 google protobuf 枚举中使用类型提示?
How to use type hinting with dictionaries and google protobuf enum?
我正在尝试使用 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 版本 < 3.7 的用户,添加引号应该有效:
from devices_pb2 import Device
def foo(device: 'Device') -> Dict[str, 'Device']:
pass
我正在尝试使用 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 版本 < 3.7 的用户,添加引号应该有效:
from devices_pb2 import Device
def foo(device: 'Device') -> Dict[str, 'Device']:
pass