我按照谷歌开发者指南中的说明创建自定义消息选项。我用了他们的例子,但我收到了一个错误:
Traceback (most recent call last):
File "test_my_opt.py", line 2, in <module>
value = my_proto_file_pb2.MyMessage.DESCRIPTOR.GetOptions().Extensions[my_proto_file_pb2.my_option]
File "(...)googleprotobufinternalpython_message.py", line 1167, in __getitem__
_VerifyExtensionHandle(self._extended_message, extension_handle)
File "(...)googleprotobufinternalpython_message.py", line 170, in _VerifyExtensionHandle
message.DESCRIPTOR.full_name))
KeyError: 'Extension "my_option" extends message type "google.protobuf.MessageOptions", but this message is of type "google.protobuf.MessageOptions".'
我只是简单地使用了以下代码:
import my_proto_file_pb2
value = my_proto_file_pb2.MyMessage.DESCRIPTOR.GetOptions().Extensions[my_proto_file_pb2.my_option]
这个原始文件:
import "beans-protobuf/proto/src/descriptor.proto";
extend google.protobuf.MessageOptions {
optional string my_option = 51234;
}
message MyMessage {
option (my_option) = "Hello world!";
}
一切都像在指南那么我应该如何访问此选项而不会出错
import "beans-protobuf/proto/src/descriptor.proto";
我认为这就是问题所在。descriptor.proto
的正确导入语句为:
import "google/protobuf/descriptor.proto";
路径字符串很重要,因为您需要扩展描述符类型的原始定义,而不是它们的某个副本。google/protobuf/descriptor.proto
成为Python中的模块google.protobuf.descriptor_pb2
,Protobuf库希望任何自定义选项都是其中类型的扩展。但您实际上是在扩展beans-protobuf/proto/src/descriptor.proto
,它在Python中变成了beans_protobuf.proto.src.descriptor_pb2
,这是一个完全不同的模块!因此,protobuf库感到困惑,认为这些扩展不适用于protobuf描述符。
我认为如果你只是更改导入语句,一切都应该正常。当protobuf正确安装后,google/protobuf/descriptor.proto
应该始终作为导入工作——不需要提供自己的文件副本。