使用 python protobuf v2.6.1 的反射时,isinstance 不起作用

isinstance doesn't work when use reflection of python protobuf v2.6.1

我正在使用 python protobuf v2.6.1 的动态反射功能,并具有如下功能:

# initilization code

        des_db_ = descriptor_database.DescriptorDatabase()
        des_pool_ = descriptor_pool.DescriptorPool(des_db_)


        fdp = descriptor_pb2.FileDescriptorProto.FromString(
            a_pb_module.DESCRIPTOR.serialized_pb)
        des_db_.Add(fdp)


def unpack_PB_msg(type_name, pb_msg_str)
        factory = message_factory.MessageFactory(des_pool_)
        msg_class = factory.GetPrototype(des_pool_.FindMessageTypeByName(type_name))

        pb_msg = msg_class()
        pb_msg.ParseFromString(pb_msg_str)

       return pb_msg

但是下面的客户端代码会失败

hello = Hello_msg()
hello_str = hello.SerializeToString()
hello2 = unpack_PB_msg(Hello_msg.DESCRIPTOR.full_name, hello_str)

hello3 = Hello_msg()
hello3.CopyFrom(hello2)# failed here!!!

错误信息是:

hello3.CopyFrom(hello2)
  File "C:\Localdata\Python27\lib\site-packages\google\protobuf\message.py", line 119, in CopyFrom
    self.MergeFrom(other_msg)
  File "C:\Localdata\Python27\lib\site-packages\google\protobuf\internal\python_message.py", line 971, in MergeFrom
    "expected %s got %s." % (cls.__name__, type(msg).__name__))
TypeError: Parameter to MergeFrom() must be instance of same class: expected Hello_msg got Hello_msg.

CopyFrom 似乎失败了,因为 isinstance 失败了。

  def MergeFrom(self, msg):
    if not isinstance(msg, cls):
      raise TypeError(
          "Parameter to MergeFrom() must be instance of same class: "
          "expected %s got %s." % (cls.__name__, type(msg).__name__))

打印hello2和hello3的数据类型时,好像不一样

hello2 : <class 'Hello_msg'>
hello3 : <class 'a_pb_module.Hello_msg'>

这是一个 protobuf 错误吗?还是我做错了什么?

这也许可以帮助某人。 我有同样的错误

TypeError: Parameter to MergeFrom() must be instance of same class: expected Hello_msg got Hello_msg.

当我在两个不同的路径中两次导入相同的 class 时,它会导致在不同的路径中导入两个不同的 classes(即使它们可能具有相同的 class 名称, Python 将它们视为两个完全不同的 class (查看 class 的 ID,您应该会发现它们是不同的)。

要解决此问题,您需要确保只导入一次相同的 class (Hello_msg)。