简体   繁体   English

如何获取python protobuf消息的枚举字段的值名称

[英]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. 我还没有进入protobuf,但我会试着说一个问题。 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. 我有消息,它是Message的一个实例,我想获取源的值就像打印消息一样。 But doing message.source gives me the code. 但是做message.source给了我代码。 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

I believe that using the EnumDescriptor as you did in your example is the only way to get an enum value's name. 我相信像你在你的例子中那样使用EnumDescriptor是获得枚举值名称的唯一方法。 You could, of course, write a helper function around it to make it less verbose. 当然,你可以在它周围写一个辅助函数,以减少它的冗长。

The EnumTypeWrapper class has a Name method, which returns the name of an enmum value. EnumTypeWrapper类有一个Name方法,它返回一个enmum值的名称。 So in this case, after importing the SourceType from Message_pb2 , SourceType.Name() will return the name for the value. 因此,在这种情况下,从Message_pb2导入SourceType后, SourceType.Name()将返回值的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM