Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all field names from a protocol buffer?

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.

like image 232
user2253332 Avatar asked Jul 08 '14 18:07

user2253332


People also ask

What is oneof in Protobuf?

Protocol Buffer (Protobuf) provides two simpler options for dealing with values that might be of more than one type. The Any type can represent any known Protobuf message type. And you can use the oneof keyword to specify that only one of a range of fields can be set in any message.

What is the difference between proto2 and proto3?

Proto3 is the latest version of Protocol Buffers and includes the following changes from proto2: Field presence, also known as hasField , is removed by default for primitive fields. An unset primitive field has a language-defined default value.

Why are Protobuf fields numbered?

Field numbers are an important part of Protobuf. They're used to identify fields in the binary encoded data, which means they can't change from version to version of your service. The advantage is that backward compatibility and forward compatibility are possible.

Can you rename Protobuf fields?

Renaming a field - With Protobuf content, the field names are only used in generated code. The field number is used to identify fields on the network. Renaming a field isn't a protocol breaking change for Protobuf. However, if a server is using JSON content then renaming a field is a breaking change.


1 Answers

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 FieldDescriptors of all the fields in message into a list:

res = message.DESCRIPTOR.fields 

To get the names of the fields "exactly as they appear in the .proto file":

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

or (from the comments):

res = message.DESCRIPTOR.fields_by_name.keys() 

To get the full names of the fields "including containing scope":

res = [field.full_name for field in message.DESCRIPTOR.fields] 
like image 167
qfiard Avatar answered Oct 16 '22 20:10

qfiard