This is tricky as the Python API (like the C++ API) has a strong sense of
ownership.  Outer messages "own" the message objects embedded inside them.
 In the Python API, this is necessary because assigning a field in an
optional sub-message may also cause the sub-message itself to become present
in the parent, and marks the parent dirty, meaning that some cached
information needs to be recomputed.  If you were allowed to append message
objects allocated externally, this could get muddled.  For example, what
happens if you do:
  message1 = parse_message(...)
  message2 = MyMessage()

Now message1 and message2 presumably share an embedded message instance.
 Then what happens when you modify the sub-message?  Both message1 and
message2 would have to be marked dirty.  So we'd have to start keeping track
of multiple parents for each message object, which is rather convoluted.

So I think the current approach will probably stay.

On Thu, Jun 11, 2009 at 6:35 PM, Dan <> wrote:

> Hello,
> I'm finding that I am writing code that looks a lot like this:
> tmpsubmessage = parse_submessage_data()
> submessage = message.submessage.add()
> submessage.MergeFrom(tmpsubmessage)
> This seems inefficient to me.  One alternative would be to create the
> new submessage, and fill it on the spot:
> submessage = message.submessage.add()
> parse_submessage_data(submessage)
> However, sometimes there's a bit of distance between when I'm
> generating the data and when I'm putting it all together (such as
> storing pre-made message sections, and loading them from a database
> later).  What I really want is an append:
> submessage = parse_submessage_data()
> message.submessage.append(submessage)
> However, I can't see any way of doing this directly.  The closest I've
> read about in the API is to create the message's parent, then merging
> the parents together (in the implementation this automatically appends
> repeated messages).  But that's impractical if the same message has
> multiple potential parents.
> Any ideas?
> Thanks,
> Daniel
> >

You received this message because you are subscribed to the Google Groups 
"Protocol Buffers" group.
To post to this group, send email to
To unsubscribe from this group, send email to
For more options, visit this group at

Reply via email to