Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 951
ruseel Avatar asked Oct 01 '18 01:10

ruseel


1 Answers

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)
like image 131
ruseel Avatar answered Oct 26 '22 23:10

ruseel