How to assign to repeated field?

梦想的初衷 提交于 2019-12-03 02:54:59

问题


I am using protocol buffers in python and I have a Person message

repeated uint64 id

but when I try to assign a value to it like:

person.id = [1, 32, 43432]

I get an error: Assigment not allowed for repeated field "id" in protocol message object How to assign a value to a repeated field ?


回答1:


As per the documentation, you aren't able to directly assign to a repeated field. In this case, you can call extend to add all of the elements in the list to the field.

person.id.extend([1, 32, 43432])



回答2:


If you don't want to extend but overwrite it completely, you can do:

person.id[:] = [1, 32, 43432]

This approach will also work to clear the field entirely:

del person.id[:]



回答3:


You can try using MergeFrom

Check out these docs for the full list of Message methods available to you: https://developers.google.com/protocol-buffers/docs/reference/python/google.protobuf.message.Message-class



来源:https://stackoverflow.com/questions/23726335/how-to-assign-to-repeated-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!