gpt4 book ai didi

python - 在 protobuf 中需要 `oneof`?

转载 作者:太空宇宙 更新时间:2023-11-03 12:26:51 24 4
gpt4 key购买 nike

我想制作一个可以包含多种不同事件类型的 protobuf Event 消息。这是一个例子:

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 文档,不推荐使用 required 字段规则,并且已在 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 时,已经广泛接受字段可能永远不应该是“必需的”,因此设计者没有费心去实现一种方法来使 oneof 成为必需的。

关于python - 在 protobuf 中需要 `oneof`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42955621/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com