Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value name of a python protobuf message's enum field

I'm not into protobuf yet, but i'll try to phrase a question. Given i have:

  enum SourceType {
     WEB = 1;
  }
  message Message {
    optional SourceType source = 6;
  }

I have message which is an instance of Message and I want to get the value of the source just like printing the message. But doing message.source gives me the code. I want to get the value just from the object, not by using other enums/mappings/constants. In the last line I have an example of how I can reach the expected value, but i'm looking for a more elegant way.

  > message    
  <Message_pb2.Message object at 0x7f78561a83c8>
  > print message
  source: WEB
  > print message.source 
  1
  > message.DESCRIPTOR.fields_by_name['source'].enum_type.values_by_number[1].name 
  WEB
like image 687
mihaicc Avatar asked Jul 30 '15 15:07

mihaicc


2 Answers

The EnumTypeWrapper class has a Name method, which returns the name of an enmum value. So in this case, after importing the SourceType from Message_pb2, SourceType.Name() will return the name for the value.

like image 104
Ferenc Pal Avatar answered Oct 09 '22 03:10

Ferenc Pal


I believe that using the EnumDescriptor as you did in your example is the only way to get an enum value's name. You could, of course, write a helper function around it to make it less verbose.

like image 33
Kenton Varda Avatar answered Oct 09 '22 04:10

Kenton Varda