Field Types¶
protoc-gen-pydantic supports all standard proto3 field types and generates correct Pydantic
annotations with appropriate defaults.
Scalar fields¶
All proto3 scalar types map to native Python types:
| Proto type | Python type | Default |
|---|---|---|
string |
str |
"" |
bool |
bool |
False |
int32, sint32, sfixed32 |
int |
0 |
uint32, fixed32 |
int |
0 |
int64, sint64, sfixed64 |
ProtoInt64 |
0 |
uint64, fixed64 |
ProtoUInt64 |
0 |
float |
float |
0.0 |
double |
float |
0.0 |
bytes |
bytes |
b"" |
ProtoInt64 and ProtoUInt64 are type aliases for int that carry JSON serialization semantics
(proto3 encodes 64-bit integers as strings in JSON).
Optional fields¶
optional fields use T | None with a default of None, distinguishing "field not set"
from the zero value:
Repeated fields¶
repeated fields generate list[T] with default_factory=list:
Map fields¶
map<K, V> fields generate dict[K, V] with default_factory=dict:
Oneof fields¶
oneof groups generate one field per variant, all typed as T | None = None.
A @model_validator is generated for each group and raises ValidationError
if more than one field is set, enforcing proto3's at-most-one semantics at
runtime.
class Payment(_ProtoModel):
credit_card: str | None = _Field(
default=None,
description='Only one of the fields can be specified with: ["credit_card", "paypal", "bank_iban"] (oneof method)',
)
paypal: str | None = _Field(
default=None,
description='Only one of the fields can be specified with: ["credit_card", "paypal", "bank_iban"] (oneof method)',
)
bank_iban: str | None = _Field(
default=None,
description='Only one of the fields can be specified with: ["credit_card", "paypal", "bank_iban"] (oneof method)',
)
@_model_validator(mode="after")
def _validate_oneof_method(self) -> "Payment":
_set = [
f
for f in ("credit_card", "paypal", "bank_iban")
if getattr(self, f) is not None
]
if len(_set) > 1:
raise ValueError(f"oneof 'method': only one field may be set, got {_set!r}")
return self
Message fields¶
Message-typed fields default to None (not an empty sub-message):
Enum fields¶
Enum-typed fields also default to None. See the Enums page for full details.