protobuf
Protobuf core primitives and features.
DescFieldValue
module-attribute
DescFieldValue = (
DescFieldValueScalar
| DescFieldValueMessage
| DescFieldValueEnum
| DescFieldValueMap
| DescFieldValueList
)
Describes the value of a field declaration in a protobuf source file.
DescFieldValueSingular
module-attribute
DescFieldValueSingular = (
DescFieldValueScalar
| DescFieldValueMessage
| DescFieldValueEnum
)
Describes the value of a non-repeated, non-map field declaration in a protobuf source file.
maximum_supported_edition
module-attribute
maximum_supported_edition = Edition(_MAXIMUM_EDITION)
The maximum protobuf edition supported by this implementation.
minimum_supported_edition
module-attribute
minimum_supported_edition = Edition(_MINIMUM_EDITION)
The minimum protobuf edition supported by this implementation.
DescComments
dataclass
Comments associated with a protobuf source location.
Attributes:
| Name | Type | Description |
|---|---|---|
leading_detached |
Sequence[str]
|
Paragraphs of comments that appear before (but not connected to) the element. |
leading |
str | None
|
Comment appearing before the element, if any. |
trailing |
str | None
|
Comment appearing after the element, if any. |
source_path |
Sequence[int]
|
The source code info path identifying the element. |
DescEnum
dataclass
DescEnum(
type_name,
name,
file,
parent,
open,
values,
deprecated,
proto,
_values_by_number,
_values_by_name,
_local_name,
_local_qualname,
*,
_type=None,
)
Describes an enumeration in a protobuf source file.
Attributes:
| Name | Type | Description |
|---|---|---|
type_name |
str
|
The fully qualified name of the enumeration. (We omit the leading dot.) |
name |
str
|
The name of the enumeration, as declared in the protobuf source. |
file |
DescFile
|
The file this enumeration was declared in. |
parent |
DescMessage | None
|
The parent message, if this enumeration was declared inside a message declaration. |
open |
bool
|
Enumerations can be open or closed. See https://protobuf.dev/programming-guides/enum/. |
values |
Sequence[DescEnumValue]
|
Values declared for this enumeration. |
deprecated |
bool
|
Marked as deprecated in the protobuf source. |
proto |
EnumDescriptorProto
|
The compiler-generated descriptor. |
DescEnumValue
dataclass
Describes an individual value of an enumeration in a protobuf source file.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The name of the enumeration value, as specified in the protobuf source. |
local_name |
str
|
A safe and idiomatic name for the value in Python. |
parent |
DescEnum
|
The enumeration this value belongs to. |
number |
int
|
The numeric enumeration value, as specified in the protobuf source. |
deprecated |
bool
|
Marked as deprecated in the protobuf source. |
proto |
EnumValueDescriptorProto
|
The compiler-generated descriptor. |
DescExtension
dataclass
DescExtension(
name,
value,
type_name,
file,
parent,
extendee,
number,
json_name,
deprecated,
presence,
proto,
*,
_type=None,
)
Describes an extension in a protobuf source file.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The field name, as specified in the protobuf source. |
value |
DescFieldValueScalar | DescFieldValueMessage | DescFieldValueEnum | DescFieldValueList
|
Description of the value of the extension field. |
type_name |
str
|
The fully qualified name of the extension. |
file |
DescFile
|
The file this extension was declared in. |
parent |
DescMessage | None
|
The parent message, if this extension was declared inside a message declaration. |
extendee |
DescMessage
|
The message that this extension extends. |
number |
int
|
The field number, as specified in the protobuf source. |
json_name |
str
|
The field name in JSON. |
deprecated |
bool
|
Marked as deprecated in the protobuf source. |
presence |
SupportedFieldPresence
|
Presence of the field. See https://protobuf.dev/programming-guides/field_presence/. |
proto |
FieldDescriptorProto
|
The compiler-generated descriptor. |
DescField
dataclass
Describes a field declaration in a protobuf source file.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The field name, as specified in the protobuf source. |
value |
DescFieldValue
|
Description of the value of the field. |
parent |
DescMessage
|
The message this field is declared on. |
local_name |
str
|
A safe and idiomatic name for the field as a property in Python. |
number |
int
|
The field number, as specified in the protobuf source. |
json_name |
str
|
The field name in JSON. |
deprecated |
bool
|
Marked as deprecated in the protobuf source. |
presence |
SupportedFieldPresence
|
Presence of the field. See https://protobuf.dev/programming-guides/field_presence/. |
proto |
FieldDescriptorProto
|
The compiler-generated descriptor. |
DescFieldValueEnum
dataclass
Describes the value of an enum field declaration in a protobuf source file.
Attributes:
| Name | Type | Description |
|---|---|---|
enum |
DescEnum
|
The enum type. |
default_value |
int | None
|
The default value for the enum field. |
oneof |
DescOneof | None
|
The |
DescFieldValueList
dataclass
Describes the value of a repeated field declaration in a protobuf source file.
Attributes:
| Name | Type | Description |
|---|---|---|
element |
DescMessage | DescEnum | ScalarType
|
The element type of the repeated field. |
packed |
bool
|
Pack this repeated field? Only valid for repeated enum fields, and for repeated scalar fields except BYTES and STRING. |
delimited_encoding |
bool
|
Encode the message delimited (a.k.a. proto2 group encoding), or length-prefixed? |
DescFieldValueMap
dataclass
Describes the value of a map field declaration in a protobuf source file.
Attributes:
| Name | Type | Description |
|---|---|---|
key |
ScalarType
|
The scalar map key type. |
value |
ScalarType | DescMessage | DescEnum
|
The map value type. |
DescFieldValueMessage
dataclass
Describes the value of a message field declaration in a protobuf source file.
Attributes:
| Name | Type | Description |
|---|---|---|
message |
DescMessage
|
The message type. |
delimited_encoding |
bool
|
Encode the message delimited (a.k.a. proto2 group encoding), or length-prefixed? |
oneof |
DescOneof | None
|
The |
DescFieldValueScalar
dataclass
Describes the value of a scalar field declaration in a protobuf source file.
Attributes:
| Name | Type | Description |
|---|---|---|
scalar |
ScalarType
|
The scalar type. |
default_value |
str | bool | int | float | bytes | None
|
The default value for the scalar field. |
oneof |
DescOneof | None
|
The |
DescFile
dataclass
Describes a protobuf source file.
Attributes:
| Name | Type | Description |
|---|---|---|
edition |
int
|
The edition of the protobuf file. Will be EDITION_PROTO2 for syntax="proto2", EDITION_PROTO3 for syntax="proto3". |
name |
str
|
The name of the protobuf file, for example |
dependencies |
Sequence[DescFile]
|
Files imported by this file. |
enums |
Sequence[DescEnum]
|
Top-level enumerations declared in this file. Note that more enumerations might be declared within message declarations. |
messages |
Sequence[DescMessage]
|
Top-level messages declared in this file. Note that more messages might be declared within message declarations. |
extensions |
Sequence[DescExtension]
|
Top-level extensions declared in this file. Note that more extensions might be declared within message declarations. |
services |
Sequence[DescService]
|
Services declared in this file. |
deprecated |
bool
|
Marked as deprecated in the protobuf source. |
proto |
FileDescriptorProto
|
The compiler-generated descriptor. |
DescMessage
dataclass
DescMessage(
type_name,
name,
file,
parent,
fields,
oneofs,
members,
nested_enums,
nested_messages,
nested_extensions,
deprecated,
proto,
_local_name,
_local_qualname,
*,
_type=None,
)
Describes a message declaration in a protobuf source file.
Attributes:
| Name | Type | Description |
|---|---|---|
type_name |
str
|
The fully qualified name of the message. (We omit the leading dot.) |
name |
str
|
The name of the message, as specified in the protobuf source. |
file |
DescFile
|
The file this message was declared in. |
parent |
DescMessage | None
|
The parent message, if this message was declared inside a message declaration. |
fields |
Sequence[DescField]
|
Fields declared for this message, including fields declared in a oneof group. |
oneofs |
Sequence[DescOneof]
|
Oneof groups declared for this message. This does not include synthetic oneofs for proto3 optionals. |
members |
Sequence[DescField | DescOneof]
|
Standalone fields and oneof groups for this message, ordered by their appearance in the protobuf source. |
nested_enums |
Sequence[DescEnum]
|
Enumerations declared within the message, if any. |
nested_messages |
Sequence[DescMessage]
|
Messages declared within the message, if any. This does not include synthetic messages like map entries. |
nested_extensions |
Sequence[DescExtension]
|
Extensions declared within the message, if any. |
deprecated |
bool
|
Marked as deprecated in the protobuf source. |
proto |
DescriptorProto
|
The compiler-generated descriptor. |
DescMethod
dataclass
Describes an RPC declaration in a protobuf source file.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The name of the RPC, as specified in the protobuf source. |
parent |
DescService
|
The parent service. |
method_kind |
Literal['unary', 'server_streaming', 'client_streaming', 'bidi_streaming']
|
One of the four available method types: "unary", "server_streaming", "client_streaming", "bidi_streaming". |
input |
DescMessage
|
The message type for requests. |
output |
DescMessage
|
The message type for responses. |
idempotency |
IdempotencyLevel
|
The idempotency level declared in the protobuf source, if any. |
deprecated |
bool
|
Marked as deprecated in the protobuf source. |
proto |
MethodDescriptorProto
|
The compiler-generated descriptor. |
DescOneof
dataclass
Describes a oneof group in a protobuf source file.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The name of the oneof group, as specified in the protobuf source. |
local_name |
str
|
A safe and idiomatic name for the oneof group as a property in Python. |
parent |
DescMessage
|
The message this oneof group was declared in. |
fields |
Sequence[DescField]
|
The fields declared in this oneof group. |
proto |
OneofDescriptorProto
|
The compiler-generated descriptor. |
DescService
dataclass
Describes a service declaration in a protobuf source file.
Attributes:
| Name | Type | Description |
|---|---|---|
type_name |
str
|
The fully qualified name of the service. (We omit the leading dot.) |
name |
str
|
The name of the service, as specified in the protobuf source. |
file |
DescFile
|
The file this service was declared in. |
methods |
Sequence[DescMethod]
|
The RPCs this service declares. |
deprecated |
bool
|
Marked as deprecated in the protobuf source. |
proto |
ServiceDescriptorProto
|
The compiler-generated descriptor. |
DescUnknownField
dataclass
Description of an unknown field in a protobuf message.
When a [Message][] is parsed from data with fields not present in the message definition, those fields are stored as unknown fields. This class can be initialized and passed to container methods to access structured data in unknown fields.
Attributes:
| Name | Type | Description |
|---|---|---|
number |
int
|
The field number of the unknown field. |
value |
DescFieldValue
|
Description of the value of the unknown field. |
Enum
Bases: IntEnum
Base class for protobuf enumeration types.
Protobuf enumerations are integer-based. This class inherits from IntEnum
so enum values work as integers while maintaining a link to the protobuf
descriptor.
Generated enum classes inherit from this base class and define their enum values as class attributes.
Examples:
from protobuf import Enum
# Generated from:
# enum Color {
# COLOR_UNSPECIFIED = 0;
# COLOR_RED = 1;
# COLOR_GREEN = 2;
# }
class Color(Enum):
UNSPECIFIED = 0 # Python name (prefix stripped)
RED = 1
GREEN = 2
# Use like a regular int
color = Color.RED
print(color) # Prints: RED (Python member name)
print(repr(color)) # Color.RED (Python qualified name)
print(int(color)) # 1
print(color + 1) # 2
print(color == 1) # True
# Access the descriptor
desc = Color.desc()
print(desc.name) # "Color"
__str__
Return a string representation of the enum value.
Returns the Python member name (e.g., "RED") for known values, or the integer as a string for unknown values.
Returns:
| Type | Description |
|---|---|
str
|
The Python member name if known, otherwise the integer as a string. |
Examples:
__repr__
Return a detailed string representation of the enum value.
Returns the qualified Python name (e.g., "Color.RED") for known values, or "Color(99)" format for unknown values.
Returns:
| Type | Description |
|---|---|
str
|
The qualified Python name if known, otherwise the class name with integer. |
Examples:
desc
classmethod
Get the descriptor for this enumeration type.
Returns:
| Type | Description |
|---|---|
DescEnum
|
The DescEnum descriptor for this enum. |
Examples:
Extension
Bases: Generic[M, E]
A protobuf extension field.
Extensions allow adding fields to a message without modifying the original message definition. This class provides type-safe access to extension fields on messages.
This is meant for the generated code. For dynamic extensions use
DescExtension.type.
Attributes:
| Name | Type | Description |
|---|---|---|
desc |
DescExtension
|
The extension descriptor. |
Examples:
# Given a protobuf extension definition:
# extend Foo {
# optional string extra = 1000;
# }
from .gen.ext_pb import ext_extra # The generated extension instance.
from .gen.foo_pb import Foo
foo = Foo()
# Set a new extension value
foo[ext_extra] = "new value"
# Access the extension value
value = foo[ext_extra]
# Check if extension is set and clear it
if ext_extra in foo:
del foo[ext_extra]
Message
Bases: Generic[FieldNamesT]
Base class for Protobuf message types.
Most Message subclasses are generated from .proto files. A message instance
behaves like a regular Python object: construct it with keyword arguments using
Python field names, then read and assign fields through attributes. Message
provides all the shared runtime behavior for operating on messages.
Thread safety
Message instances are not thread safe for concurrent mutation with any other operation. Concurrent reads without mutation are safe.
Examples:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Any
|
Field names (Python local names) and their values. |
{}
|
to_json
to_json(
*,
registry=None,
always_emit_implicit=False,
print_enums_as_ints=False,
use_proto_field_name=False,
)
Serialize this message to a ProtoJSON string.
By default, fields with implicit presence are not serialized if they are set to their zero value.
A registry is required to serialize google.protobuf.Any fields and extensions. Extensions not found in the registry are silently omitted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
registry
|
Registry | None
|
A registry for resolving google.protobuf.Any messages and extensions. |
None
|
always_emit_implicit
|
bool
|
By default, fields with implicit presence
are omitted when set to their zero value (e.g. an empty
list, a proto3 int32 field with value 0). If |
False
|
print_enums_as_ints
|
bool
|
By default, the enum value name as defined
in Protobuf is used. If |
False
|
use_proto_field_name
|
bool
|
By default, field names use the
json_name field option, which defaults to lowerCamelCase.
If |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a google.protobuf.Any field cannot be resolved through the registry. |
to_binary
__repr__
Return a string representation in __init__ syntax.
Unknown fields and extensions are not included in the output.
__replace__
Create a copy by replacing fields.
Similar to dataclasses.replace(), creates a shallow copy of the message
with the specified fields updated to new values. This method is designed
to work with copy.replace() available in Python 3.13+.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Any
|
Field names and their new values. |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
A new message instance with the specified fields replaced. |
Raises:
| Type | Description |
|---|---|
AttributeError
|
If an unknown field name is provided. |
Examples:
__setattr__
Set a field or oneof attribute by local name.
Raises:
| Type | Description |
|---|---|
AttributeError
|
If name is not a known field, oneof, or internal attribute. |
has_field
Check if a field is set by its proto name (e.g., msg.has_field("field_name")).
This can be used to check whether a field with explicit presence has been set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
FieldNamesT
|
The proto field name as a string. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If the field does not exist on this message. |
clear_field
Clear a field by its proto name (e.g., msg.clear_field("field_name")).
This can be used to clear a field with explicit presence or reset a value to its default.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
FieldNamesT
|
The proto field name as a string. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the field does not exist on this message. |
__getitem__
__getitem__(key: DescField | DescUnknownField) -> Any
__getitem__(key: Extension[M, E]) -> E
Get a field value by descriptor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
DescField | DescUnknownField | Extension
|
A |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The field value, or the default if unset. For message fields the
default is |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the field does not exist on this message. |
TypeError
|
If the key is not a DescField, DescUnknownField, or Extension. |
__setitem__
__setitem__(
key: DescField | DescUnknownField, value: Any
) -> None
__setitem__(key: Extension[M, E], value: E) -> None
Set a field value by descriptor or proto name.
Fields in a oneof can be set like regular fields, which resets siblings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
DescField | DescUnknownField | Extension
|
A |
required |
value
|
Any
|
The value to assign. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the field does not exist on this message. |
TypeError
|
If the key is not a DescField, DescUnknownField, or Extension. |
__contains__
__contains__(key: DescField | DescUnknownField) -> bool
Check if a field is set (e.g., desc in msg).
For fields with explicit presence, checks if the field has been set. For fields without presence (implicit presence), compares against the default value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
DescField | DescUnknownField | Extension
|
A |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If the field does not exist on this message. |
TypeError
|
If the key is not a DescField, DescUnknownField, or Extension. |
__delitem__
__delitem__(key: DescField | DescUnknownField) -> None
__delitem__(key: Extension[M, E]) -> None
Clear a field by its key (e.g., del msg[desc]).
Clears the field to its default value. Does not delete the attribute.
For message fields, sets to None; for scalars, the zero value;
for repeated/map fields, clears to an empty list/dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
DescField | DescUnknownField | Extension
|
A |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the field does not exist on this message. |
TypeError
|
If the key is not a DescField, DescUnknownField, or Extension. |
__eq__
Compare two messages for equality.
Two messages are considered equal when all of the following hold:
- They have the same type.
- For every field, both messages agree on whether the field is set or unset.
- All set fields have equal values.
NaN-valued floats are treated as equal to each other, consistent with
Python's container equality semantics (e.g. list, dict).
Extensions and unknown fields are not considered in the comparison.
from_json
classmethod
Create a new message from a ProtoJSON string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
json
|
str | bytes | bytearray
|
A str, bytes, or bytearray instance containing the ProtoJSON. |
required |
ignore_unknown_fields
|
bool
|
Proto3 JSON parser should reject unknown fields by default. This option ignores unknown fields in parsing, as well as unrecognized enum string representations. |
False
|
registry
|
Registry | None
|
This option is required to read |
None
|
Raises:
| Type | Description |
|---|---|
JSONDecodeError
|
If json_source is not valid JSON. |
TypeError
|
If the JSON structure does not match expected types. |
ValueError
|
If a google.protobuf.Any or an extension cannot be resolved through the registry. |
from_binary
classmethod
Create a new message by parsing serialized binary data.
To merge into an existing message, use [merge_from_binary][].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
bytes
|
Serialized binary protobuf data. |
required |
ignore_unknown_fields
|
bool
|
If |
False
|
Oneof
Bases: Generic[C, V]
A oneof value with a field name and typed value.
This class represents a oneof field value in protobuf messages. It combines a field name (the field name within the oneof) with its typed value, enabling type-safe pattern matching.
Attributes:
| Name | Type | Description |
|---|---|---|
field |
Final[C]
|
The name of the active oneof field |
value |
Final[V]
|
The typed value for this field |
Examples:
a = Oneof(field="a", value="hello")
match a:
case Oneof(field="a", value=v):
print(f"Got string: {v}")
case Oneof(field="b", value=v):
print(f"Got int: {v}")
# Got string: hello
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field
|
C
|
The name of the active oneof field |
required |
value
|
V
|
The typed value for this field |
required |
Registry
A set of descriptors for files, messages, enums, extensions, and services.
See [add][] for more details.
add
Add types, descriptors, or other registries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
Registry | DescFile | DescMessage | DescEnum | DescExtension | DescService | Extension | type[Message | Enum]
|
Types, descriptors, or registries to add. All entries from registries are copied. In case of duplicates, the last entry wins. For DescFile, the types and descriptors from the defined files are all collected into this registry. For DescMessage, the message itself and all nested types are collected into this registry. |
()
|
file
message
Look up a message descriptor by its fully qualified name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
type_name
|
str
|
The fully qualified name of the message. |
required |
Returns:
| Type | Description |
|---|---|
DescMessage | None
|
The descriptor for the message, or |
service
Look up a service descriptor by its fully qualified name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
type_name
|
str
|
The fully qualified name of the service. |
required |
Returns:
| Type | Description |
|---|---|
DescService | None
|
The descriptor for the service, or |
enum
extension
Look up an extension descriptor by its fully qualified name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
type_name
|
str
|
The fully qualified name of the extension. |
required |
Returns:
| Type | Description |
|---|---|
DescExtension | None
|
The descriptor for the extension, or |
extension_for
Look up an extension by the message it extends and field number.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
type_info
|
DescMessage | str | Message
|
The extended message, either as a DescMessage or its fully qualified name. |
required |
number
|
int
|
The extension field number. |
required |
Returns:
| Type | Description |
|---|---|
DescExtension | None
|
The descriptor for the extension, or |
enum_is_unknown
Check if an enum value is unknown (i.e., not defined in the protobuf schema).
merge_from_binary
Parse serialized binary data, merging fields into an existing message.
Merge rules by field kind:
- Scalar and enum: the existing value is overwritten.
- Message: recursively merged if already present, otherwise set.
- Repeated: elements are appended.
- Map: entries are added; existing keys are overwritten. Message-valued map entries are not merged.
- Unknown fields: retained unless
ignore_unknown_fieldsisTrue.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
Message
|
The message instance to merge into. |
required |
data
|
bytes
|
Serialized binary protobuf data. |
required |
ignore_unknown_fields
|
bool
|
If |
False
|
merge_from_json
Parse a ProtoJSON string, merging fields into an existing message.
Merge rules by field kind:
- Scalar and enum: the existing value is overwritten.
- Message: recursively merged if already present, otherwise set.
- Repeated: elements are appended.
- Map: entries are added; existing keys are overwritten. Message-valued map entries are not merged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
Message
|
The message instance to merge into. |
required |
json
|
str | bytes | bytearray
|
A str, bytes, or bytearray instance containing the ProtoJSON. |
required |
ignore_unknown_fields
|
bool
|
If |
False
|
registry
|
Registry | None
|
Required to read google.protobuf.Any and extensions from JSON format. |
None
|
Raises:
| Type | Description |
|---|---|
JSONDecodeError
|
If json_source is not valid JSON. |
TypeError
|
If the JSON structure does not match expected types. |
ValueError
|
If a google.protobuf.Any or an extension cannot be resolved through the registry. |
message_from_json_value
Converts the Python value parsed from JSON data to a new Message of the given type.
This can be useful when embedding a message within a larger structure encoded as JSON. The JSON data will be read using ProtoJSON semantics, including support for well-known-types and extensions if a registry is provided.
See [message_to_json_value][] for the inverse operation.
Examples:
# For example, a request to a task runner
data = json.loads(
'{"task": "save_user", "user": {"name": "Alice", "created_at": "2024-01-01T00:00:00Z"}}'
)
user = message_from_json_value(User, data["user"])
assert user.name == "Alice"
assert user.created_at == Timestamp.from_datetime(
datetime(2024, 1, 1, tzinfo=timezone.utc)
)
merge_from
Merges the fields from source into target.
Merge rules by field kind:
- Scalar and enum: the existing value is overwritten.
- Message: recursively merged if already present, otherwise set.
- Repeated: elements are appended.
- Map: entries are added; existing keys are overwritten. Message-valued map entries are not merged.
- Unknown fields: retained unless
ignore_unknown_fieldsisTrue.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target
|
T
|
The message instance to merge into. |
required |
source
|
T
|
The message instance to merge from. |
required |
ignore_unknown_fields
|
bool
|
Whether to ignore unknown fields during the merge. |
False
|
message_to_json_value
message_to_json_value(
message,
/,
*,
registry=None,
always_emit_implicit=False,
print_enums_as_ints=False,
use_proto_field_name=False,
)
Converts a protobuf message to a Python value that can be encoded as JSON.
This can be useful when embedding a message within a larger structure encoded as JSON. The message content is converted using ProtoJSON semantics, including support for well-known-types and extensions if a registry is provided.
See [message_from_json_value][] for the inverse operation.
Examples:
user = User(
name="Alice", created_at=Timestamp.from_datetime(datetime(2024, 1, 1))
)
# For example, a request to a task runner
request = {"task": "save_user", "user": message_to_json_value(user)}
assert (
json.dumps(request)
== '{"task": "save_user", "user": {"name": "Alice", "createdAt": "2024-01-01T00:00:00Z"}}'
)