ruseel
ruseel

Reputation: 1734

protobuf3, python - How to set element to map<string,OtherMessage> dict?

When I tried to set element of a map<string,Y> dict of X ValueError raised.

"Direct assignment of submessage not allowed"

My experiment code is

syntax = "proto3";

message X {
  map<string,Y> dict = 1;
}

message Y {
  int32 v = 1;
}

And python code

x = x_pb2.X()
y = x_pb2.Y()
x.data['a'] = y

then error raised

Traceback (most recent call last):
  File "x.py", line 8, in <module>
    x.data['a'] = y
ValueError: Direct assignment of submessage not allowed

How can I work around this problem?

Upvotes: 9

Views: 8900

Answers (1)

ruseel
ruseel

Reputation: 1734

I guess this is optimal usage pattern

x = x_pb2.X()
x.data['a'].v = 1

And another option is using CopyFrom

x = x_pb2.X()
y = x_pb2.Y()
y.v=2
x.data['a'].CopyFrom(y)

Upvotes: 12

Related Questions