+-
python – 在protobuf中需要`oneof`?
我想制作一个可以包含几种不同事件类型的protobuf事件消息.这是一个例子:

message Event {
    required int32 event_id = 1;

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

这很好用,但有一点让我感到困惑的是EventType是可选的:我只能编码一个只有event_id的对象,而protobuf不会抱怨.

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

有没有办法要求设置EventType?如果重要的话,我正在使用Python.

最佳答案
根据Protocol Buffers文档,不建议使用必需的字段规则,并且已在proto3中删除.

Required Is Forever You should be very careful about marking fields as required. If at some point you wish to stop writing or sending a required field, it will be problematic to change the field to an optional field – old readers will consider messages without this field to be incomplete and may reject or drop them unintentionally. You should consider writing application-specific custom validation routines for your buffers instead. Some engineers at Google have come to the conclusion that using required does more harm than good; they prefer to use only optional and repeated. However, this view is not universal.

正如上面的文档所说,您应该考虑使用特定于应用程序的验证,而不是根据需要标记字段.

没有办法将oneof标记为“必需”(即使在proto2中),因为在引入oneof时,已经广泛接受的是,字段可能永远不应该是“必需的”,因此设计人员没有打扰实现方式做一个必要的.

点击查看更多相关文章

转载注明原文:python – 在protobuf中需要`oneof`? - 乐贴网