Getting all field names from a protocol buffer?

后端 未结 3 1973
予麋鹿
予麋鹿 2021-02-02 08:22

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.

3条回答
  •  你的背包
    2021-02-02 09:17

    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]
    

提交回复
热议问题