Reputation: 39174
Accordingly to protocol buffer python generated code documentation, I can add a object to a repeated message field this way:
foo = Foo()
bar = foo.bars.add() # Adds a Bar then modify
bar.i = 15
foo.bars.add().i = 32 # Adds and modify at the same time
but:
how can I remove bar
from bars
?
how can I remove the n-th
bar element from bars
?
Upvotes: 2
Views: 3496
Reputation: 37269
It took me more than a few minutes to get the proto buffer compiler installed correctly, so that may be reason enough to ignore this :)
Although it isn't in the documentation, you can actually treat a repeated field much like a normal list. Aside from its private methods, it supports add
, extend
, remove
and sort
, and remove
is what you are looking for in the first case:
foo.bars.remove(bar)
Here is the output when printing foo
before the above line (as defined by your code above) and after:
Original foo: bars { i: 15 } bars { i: 32 } foo without bar: bars { i: 32 }
As for removing the nth
element, you can use del
and the index position you want to delete:
# Delete the second element
del foo.bars[1]
And the output:
Original foo: bars { i: 15 } bars { i: 32 } Removing index position 1: bars { i: 15 }
Hope that helps!
Upvotes: 4