Dereck Wonnacott
Dereck Wonnacott

Reputation: 493

How can I remove an item from a repeated protobuf field in python?

I have a protobuf message that contains a repeated field. I would like to remove one of the items in the list but I can't seem to find a good way to do so without copying all of the items out of the repeated field into a list, clearing the repeated field, and repopulating it.

In C++ there is a RemoveLast() function, but this doesn't seem to appear in the python API...

Upvotes: 21

Views: 27142

Answers (3)

neck
neck

Reputation: 47

const google::protobuf::Descriptor  *descriptor = m_pMessage->GetDescriptor();
const google::protobuf::Reflection  *reflection = m_pMessage->GetReflection();
const google::protobuf::FieldDescriptor* field = descriptor->FindFieldByName("my_list_name");
if (i<list_size-1)
{
    reflection->SwapElements(m_pMessage, field, i, list_size-1);
}
reflection->RemoveLast(m_pMessage, field);

Upvotes: -1

nneonneo
nneonneo

Reputation: 179452

As noted in the documentation, the object wrapping a repeated field in Protobuf behaves like a regular Python sequence. Therefore, you should be able to simply do

del foo.fields[index]

For example, to remove the last element,

del foo.fields[-1]

Upvotes: 26

Raymond Tau
Raymond Tau

Reputation: 3469

In Python, deleting an element from a list could be done in this way:

list.remove(item_to_be_removed)

or

del list[index]

Upvotes: 2

Related Questions