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
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.
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_ .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With