Require `oneof` in protobuf?

I want to create a protobuf post Event

that can contain several different types of events. Here's an example:

message Event {
    required int32 event_id = 1;

    oneof EventType {
        FooEvent foo_event = 2;
        BarEvent bar_event = 3;
        BazEvent baz_event = 4;
    }
}

      

This works great, but one thing that worries me is that EventType

it is optional: I can only encode the object with event_id

, and protobuf won't complain.

>>> e = test_pb2.Event()
>>> e.IsInitialized()
False
>>> e.event_id = 1234
>>> e.IsInitialized()
True

      

Is there a way to install EventType

? I am using Python if it matters.

+3


source to share


1 answer


According to the Protocol Buffer document, the field rule required

is deprecated and has already been removed in proto3.

It takes forever. You must be very careful when labeling the fields as needed. If at some point you want to stop writing or submit the required field, it will be problematic to change the field to an optional field. Older readers will consider posts without this field to be incomplete and may inadvertently reject or discard them. You should consider writing application-specific validation routines for your buffers instead . Some Google engineers have found that using the required tools is doing more harm than good; they prefer to use only optional and repetitive ones. However, this opinion is not universal.



And as the document above says, you should consider using application validation instead of marking the fields as required

.

Can't be marked oneof

as "required" (even in proto2) because it oneof

was already assumed at the time of input that fields should probably never be "required" and so the designers didn't bother to implement a way to make it oneof

mandatory.

+8


source







All Articles