Search code examples
pythonlistdictionaryprotocol-buffers

Adding a primitive type repeated field in a protobuf from python


I have a proto2 file defined like the following:

message X {
  repeated A a = 1;
  repeated B b = 2;
}

message BtoOtherBEntry {
  required uint64 parent_b = 1; // key
  repeated uint64 children_b = 2; // value
}

Then I have a python code that maps a type uint64 B to a list of B. Let's say this is BtoBMap.

I am trying to populate X.b

        X x
        for key, values in self.BtoBMap.items():
            if len(values) > 0:
                b_to_b_entry = x.b.add()
                b_to_b_entry.parent_b = key
                b_to_b_entry.children_b.extend(values)

I have tried looping and using add and also tried append which I don' think is defined in proto2. extend doesn't work. How else can I assign these values?


Solution

  • With foo.proto:

    syntax = "proto2";
    
    message A {}
    message B {}
    
    message X {
      repeated A a = 1;
      repeated B b = 2;
    }
    

    A and B defined so the proto compiles.

    You can:

    import foo_pb2;
    
    # Create parent
    x = foo_pb2.X()
    
    # Create children
    a = foo_pb2.A()
    b = foo_pb2.B()
    
    # Either extend with (existing) children
    x.a.extend([a,a])
    
    # Or append with (existing) children
    x.b.append(b)
    x.b.append(b)
    
    # Or add to create child(ren)
    aa = x.a.add()
    bb = x.b.add()
    
    print(x)
    

    Yields:

    a {
    }
    a {
    }
    a {
    }
    b {
    }
    b {
    }
    b {
    }