How to get top-level protobuf enum value name by number in python? How to get top-level protobuf enum value name by number in python? python python

How to get top-level protobuf enum value name by number in python?


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')