1 | initial version |
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.