How to assign to repeated field?

2020-05-13 20:29发布

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 ?

4条回答
Evening l夕情丶
2楼-- · 2020-05-13 20:53

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])
查看更多
Emotional °昔
3楼-- · 2020-05-13 20:56

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[:]
查看更多
Emotional °昔
4楼-- · 2020-05-13 21:07

For repeated composite types this is what worked for me.

del person.things[:]
person.things.extend([thing1, thing2, ..])

taken from these comments How to assign to repeated field? How to assign to repeated field?

查看更多
The star\"
5楼-- · 2020-05-13 21:10

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

查看更多
登录 后发表回答