Getting all field names from protocol buffer?

I want to get all the proto field names in the list. Is there any way to do this? I looked at the documentation, and there seemed to be nothing for it.

+8
python protocol-buffers
source share
2 answers

Each proto class has a DESCRIPTOR class variable, which can be used to check the fields of the corresponding protobuf messages.

See the Descriptor and FieldDescriptor documentation for more details.

Here is a simple example to get the names of all the fields in message in a list:

 res = list(message.DESCRIPTOR.fields) 
+8
source share

Qfiard's answer did not work for me. The message.DESCRIPTOR.fields.keys() call was created by AttributeError: 'list' object has no attribute 'keys' .

Not sure why this will not work. Perhaps this has something to do with how the message was defined / compiled.

Workaround consisted in compiling a list of individual field objects and getting the name property for each. This gave me a list of the rows of all the fields in this list.

 res = [f.name for f in message.DESCRIPTOR.fields] 

Note that this does not give you field names inside these fields recursively.

+11
source share

All Articles