I want to get all the field names of a proto into a list. Is there a way to do this? I looked in the documentation and there doesn't seem to be anything for this.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Every proto class possess a DESCRIPTOR class variable that can be used to inspect the fields of corresponding protobuf messages.
Have a look at the documentation of the Descriptor and FieldDescriptor classes for more details.
Here is a simple example to get the
FieldDescriptor
s of all the fields inmessage
into a list:To get the names of the fields "exactly as they appear in the .proto file":
or (from the comments):
To get the full names of the fields "including containing scope":
qfiard's answer didn't work for me. Calling
message.DESCRIPTOR.fields.keys()
producedAttributeError: 'list' object has no attribute 'keys'
.Not sure why it wouldn't work. Maybe it has something to do with how the message was defined/compiled.
The workaround was to do a list composition of the individual field objects and get the
name
property for each. This gave me a list of strings of all fields in this list.Note that this does not get you the field names within those fields recursively.
You can easily get a list of fields as follows