如何在Python中设置一个空消息的ProtoBuf字段?

时间:2015-04-15 06:44:11

标签: python protocol-buffers

以下是Google协议缓冲区(.proto)文件的内容

message First
{
    required uint32 field1 = 1;

    optional MessageType1 request = 2;
}

message MessageType1
{
}

我想设置MessageType1字段请求。但我认为这是一个错误:

AttributeError: Assignment not allowed to composite field "request" in protocol message object.

如何在Python中设置此空消息的值?

1 个答案:

答案 0 :(得分:9)

在Proto Buffer的Message类的源代码中得到了这个。

  def SetInParent(self):
    """Mark this as present in the parent.

    This normally happens automatically when you assign a field of a
    sub-message, but sometimes you want to make the sub-message
    present while keeping it empty.  If you find yourself using this,
    you may want to reconsider your design."""

所以设置这样一个空消息的方法是调用这个函数:

first.request.SetInParent()