Ask Your Question
4

How to convert a Pydantic model which uses recursion into a gRPC protobuf format?

asked 2023-07-18 16:59:57 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-07-18 17:24:02 +0000

scrum gravatar image

When converting a Pydantic model that uses recursion into a gRPC protobuf format, you will need to define the nested message types for any nested models.

For example, consider the following Pydantic model:

from typing import List, Optional
from pydantic import BaseModel

class Node(BaseModel):
    label: str
    children: Optional[List['Node']] = None

To convert this to a gRPC protobuf format, you will need to define a corresponding message type:

syntax = "proto3";

message Node {
    string label = 1;
    repeated Node children = 2;
}

Note that the repeated keyword is used to indicate that children is a list.

If the nested model is used in multiple places, you may want to define it as a separate message type and reference it from the parent message types.

For example, consider a modified version of the Node model that also includes a reference to a Parent:

from pydantic import BaseModel

class Node(BaseModel):
    label: str
    parent: Optional['Parent'] = None
    children: List['Node'] = []

class Parent(BaseModel):
    label: str
    child: Optional[Node] = None

To convert this to a gRPC protobuf format, you can define the nested Node message type as a separate message:

syntax = "proto3";

message Node {
    string label = 1;
    optional Parent parent = 2;
    repeated Node children = 3;
}

message Parent {
    string label = 1;
    optional Node child = 2;
}

Note that the nested Node message type is referenced in the Parent message type.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-18 16:59:57 +0000

Seen: 11 times

Last updated: Jul 18 '23