Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access python enums in protobufs

In my protobuf file called skill.proto, I have:

message Cooking {
    enum VegeType {
        CAULIFLOWER = 0;
        CUCUMBER = 1;
    }
    required VegeType type = 1;
}

In another file (eg: name.py) I want to set the cooking type to cucumber. ie:

co = skill_pb2.Cooking()
co.type = skill_pb2.cooking.type.CUCUMBER

so that last line there doesn't work. How do I set co.type to CUCUMBER?

NB: I want to avoid doing co.type = 1

like image 378
theQuestionMan Avatar asked Dec 22 '15 02:12

theQuestionMan


People also ask

How do enums work in Protobuf?

enum is one of the composite datatypes of Protobuf. It translates to an enum in the languages that we use, for example, Java. Now our message class contains an Enum for payment. Each of them also has a position which is what Protobuf uses while serialization and deserialization.

How would you define enum in proto file?

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_ .

Can you do enums in Python?

Python's enum module provides the Enum class, which allows you to create enumeration types. To create your own enumerations, you can either subclass Enum or use its functional API. Both options will let you define a set of related constants as enum members.


1 Answers

Just a typo and some capitalization.

skill_pb2.Cooking.CUCUMBER

See https://developers.google.com/protocol-buffers/docs/pythontutorial


Update: There are now three possible methods for accessing enums in protobuf:

skill_pb2.Cooking.CUCUMBER
skill_pb2.Cooking.VegeType.CUCUMBER
skill_pb2.Cooking.VegeTypeValue.Value('CUCUMBER')

with the second one being more recent as discussed in this issue.

like image 76
dolan Avatar answered Sep 24 '22 08:09

dolan