How to initialize embedded messages in Python?

48 views
Skip to first unread message

Jens Troeger

unread,
Nov 8, 2023, 1:42:33 AM11/8/23
to Protocol Buffers
Hello,

Following up on the documentation on Singular Message Fields (link) and its examples, I’m unclear on passing messages to the initializer. Building on the existing example:

message Foo { optional Bar bar = 1; } message Bar { optional int32 i = 1; }

I am not supposed to use

foo = Foo() foo.bar = Bar() # WRONG!

but what about

foo = Foo(bar=Bar(i=5))

In this case, will the generated initializer use e.g. CopyFrom() (docs) correctly? Or is the recommendation to use:

foo = Foo() bar = Bar()foo.bar.CopyFrom(bar)

The suggestion to write directly to fields of Bar can become tedious, particulalry if Bar is more complex and I’d like to compose messages form other messages.

Much thanks!
Jens

Nathaniel Manista

unread,
Nov 8, 2023, 3:43:47 AM11/8/23
to Jens Troeger, Protocol Buffers
On Wed, Nov 8, 2023 at 7:42 AM Jens Troeger <jens.t...@gmail.com> wrote:
but what about

foo = Foo(bar=Bar(i=5))

This is the preferred form. Please consider adding your 👍 to issue 2782 about boosting the clarity of this preference in the documentation.
-N
Reply all
Reply to author
Forward
0 new messages