80

For example, I have proto-file File.proto:

enum Test {
  ONE = 1;
  TWO = 2;
}

I generate file File_pb2.py with protoc from File.proto. I want in a python-code get string "ONE" (that corresponds to the name of File_pb2.ONE) by value 1 (that corresponds to the value of File_pb2.ONE) from generated file File_pb2.py without defining my own dictionaries. How can I do that?

abyss.7
  • 13,882
  • 11
  • 56
  • 100
  • What does the generated `File_pb2.py` look like, for the code relating to `Test` ? – Marc Gravell Jul 16 '12 at 10:25
  • @MarcGravell the look of `File_pb2.py` generally depends on protoc version. The question suggests that the answer is given with regard to _standart protobuf python API_, since I can't find the answer anywhere by myself. For example, there is an answer for related problem on https://groups.google.com/forum/?fromgroups#!topic/protobuf/HRApuLNyYVQ – abyss.7 Jul 16 '12 at 10:35

1 Answers1

132

Assuming the generated python is located in File_pb2.py code Try this:

file_pb2._TEST.values_by_number[1].name

In your case, this should give 'ONE'

The reverse is :

file_pb2._TEST.values_by_name['ONE'].number

will give 1.

EDIT: As correctly pointed by @dyoo in the comments, a new method was later introduced in protobuf library:

file_pb2.Test.Name(1)
file_pb2.Test.Value('One')

EDIT: This has changed again in proto3. Now the Name() and Value() methods belong to the EnumTypeWrapper class so they can be accessed like:

file_pb2.Name(1)
file_pb2.Value('One')
Anentropic
  • 32,188
  • 12
  • 99
  • 147
Tisho
  • 8,320
  • 6
  • 44
  • 52
  • 19
    This seems low-level; you should be able to use the `Name()` method on the enumeration class to get at this more directly. e.g. `file_pb2.Test.Name(1)` should also give you "ONE". It's part of https://code.google.com/p/protobuf/source/browse/trunk/python/google/protobuf/internal/enum_type_wrapper.py?r=425 – dyoo Nov 19 '13 at 01:40
  • 2
    @dyoo I'm almost sure that there was no Name() method at the time I've written the reply(Jul 16 '12). The file you refer is been created Sep 21, '12. Anyway thank you for the comment, I'll add it in the reply. – Tisho Nov 19 '13 at 08:13
  • 1
    @dyoo, your suggestion works, but with with `types-protobuf` installed mypy complains about `file_pb2.Test` not having the attribute `Name`. – lead-free Dec 16 '22 at 15:44