Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 810
abyss.7 Avatar asked Jul 16 '12 10:07

abyss.7


People also ask

What is the difference between proto2 and Proto3?

Proto3 is the latest version of Protocol Buffers and includes the following changes from proto2: Field presence, also known as hasField , is removed by default for primitive fields. An unset primitive field has a language-defined default value.

How do I set default value in Protobuf?

For bool s, the default value is false. For numeric types, the default value is zero. For enums , the default value is the first value listed in the enum's type definition. This means care must be taken when adding a value to the beginning of an enum value list.

How does Protobuf define enum?

You can define enum s within a message definition, as in the above example, or outside – these enum s can be reused in any message definition in your .proto file. You can also use an enum type declared in one message as the type of a field in a different message, using the syntax _MessageType_._EnumType_ .


1 Answers

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') 
like image 117
Tisho Avatar answered Sep 27 '22 23:09

Tisho