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

web*_*nja 10 python protocol-buffers

以下是Google Protocol Buffer(.proto)文件的内容

message First
{
    required uint32 field1 = 1;

    optional MessageType1 request = 2;
}

message MessageType1
{
}
Run Code Online (Sandbox Code Playgroud)

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

AttributeError: Assignment not allowed to composite field "request" in protocol message object.
Run Code Online (Sandbox Code Playgroud)

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

web*_*nja 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."""
Run Code Online (Sandbox Code Playgroud)

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

first.request.SetInParent()
Run Code Online (Sandbox Code Playgroud)