Skip to main content
 首页 » 编程设计

python之protobuf3,python之如何将元素设置为 mapstring,OtherMessage> 字典

2024年12月31日27tuyile006

当我尝试设置 map<string,Y> dict of X 的元素时 引发 ValueError。

"Direct assignment of submessage not allowed"

我的实验代码是

syntax = "proto3"; 
 
message X { 
  map<string,Y> dict = 1; 
} 
 
message Y { 
  int32 v = 1; 
} 

和python代码

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

然后出现错误

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

我该如何解决这个问题?

请您参考如下方法:

我猜这是最佳使用模式

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

另一种选择是使用 CopyFrom

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