mihaicc
mihaicc

Reputation: 3102

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

Upvotes: 13

Views: 12385

Answers (3)

heboni
heboni

Reputation: 1

You can use EnumTypeWrapper.Name() method

In case there are several items in a enum, EnumTypeWrapper.Name() requires positional argument 'number', e.g.

 enum SourceType {
     DB = 0;
     WEB = 1;
 }

SourceType.Name(1) will return WEB

Upvotes: 0

Ferenc Pal
Ferenc Pal

Reputation: 154

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.

Upvotes: 7

Kenton Varda
Kenton Varda

Reputation: 45181

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.

Upvotes: 0

Related Questions