Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protobuf and Python: How to add messages to "repeatable Any" field?

I have a proto message:

syntax = "proto3";

import "google/protobuf/any.proto";

message Task {
    repeated google.protobuf.Any targets = 1;
    // ...
}

message Target {
    string name = 1;
    // ...
}

How should I add Target messages into Task.targets?

In official docs I've found info about how to assign value to a single Any type value, however in my case I have repeated Any field type.

Edit: Task.targets may contain different types of targets, that's why Any type is used. A single Target message is just for minimal reproducible example.

like image 924
Prisacari Dmitrii Avatar asked Oct 26 '25 15:10

Prisacari Dmitrii


1 Answers

Thanks @Justin Schoen. According to https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/Any, you need to first create an Any object, then Pack a Target (or any other object type) before appending it to the repeated list.

from google.protobuf.any_pb2 import Any
task = Task()
target = Any()
target.Pack(Target())
task.targets.append(any)
like image 56
matthewpark319 Avatar answered Oct 28 '25 14:10

matthewpark319