protobuf 的 HasField 函数需要什么参数?

rku*_*ska 4 python protocol-buffers

考虑以下结构

message Fly {
  uint32 dtime = 1;
}
Run Code Online (Sandbox Code Playgroud)

HasField功能不起作用:

>>> d.ListFields()[0][0].name
'dtime'
>>> d.ListFields()[0][0].full_name
'Fly.dtime'
>>> 
>>> d.HasField('dtime')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/.../lib/python2.7/site-packages/google/protobuf/internal/python_message.py", line 825, in HasField
    raise ValueError(error_msg % field_name)
ValueError: Protocol message has no non-repeated submessage field "dtime"
>>> d.HasField('Fly.dtime')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/.../lib/python2.7/site-packages/google/protobuf/internal/python_message.py", line 825, in HasField
    raise ValueError(error_msg % field_name)
ValueError: Protocol message has no non-repeated submessage field "Fly.dtime"
Run Code Online (Sandbox Code Playgroud)

HasField期望什么参数?

Dan*_*man 6

我想你误解了什么HasField()。它不检查 protobuf 类型是否通过名称定义特定字段。它所做的是检查给定消息字段的名称是否为当前实例设置了该字段。

正如文档所指出的,在 proto3 中为非消息字段调用 HasField 将引发错误。

  • @rkuska:对。在 proto3 下,没有设置/未设置整数之类的东西。只有默认/非默认。如果需要,则需要返回 proto2。至少,这是我的理解。 (2认同)