google.protobuf.message¶
Contains an abstract base class for protocol messages.
exception google.protobuf.message. DecodeError ¶
Exception raised when deserializing messages.
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
exception google.protobuf.message. EncodeError ¶
Exception raised when serializing messages.
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
exception google.protobuf.message. Error ¶
Base error type for this module.
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
class google.protobuf.message. Message ¶
Abstract base class for protocol messages.
Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.
Returns the serialized size of this message.
Recursively calls ByteSize() on all contained messages.
The number of bytes required to serialize this message.
Clears all data that was set in the message.
Clears the contents of a given extension.
extension_handle – The handle for the extension to clear.
Clears the contents of a given field.
Inside a oneof group, clears the field set. If the name neither refers to a defined field or oneof group, ValueError is raised.
field_name (str) – The name of the field to check for presence.
ValueError – if the field_name is not a member of this message.
Copies the content of the specified message into the current message.
The method clears the current message and then merges the specified message using MergeFrom.
other_msg (Message) – A message to copy into the current one.
Clears all fields in the UnknownFieldSet .
This operation is recursive for nested message.
classmethod FromString ( s ) ¶ HasExtension ( extension_handle ) ¶
Checks if a certain extension is present for this message.
Extensions are retrieved using the Extensions mapping (if present).
extension_handle – The handle for the extension to check.
Whether the extension is present for this message.
KeyError – if the extension is repeated. Similar to repeated fields, there is no separate notion of presence: a “not present” repeated extension is an empty list.
Checks if a certain field is set for the message.
For a oneof group, checks if any field inside is set. Note that if the field_name is not defined in the message descriptor, ValueError will be raised.
field_name (str) – The name of the field to check for presence.
Whether a value has been set for the named field.
ValueError – if the field_name is not a member of this message.
Checks if the message is initialized.
The method returns True if the message is initialized (i.e. all of its required fields are set).
Returns a list of (FieldDescriptor, value) tuples for present fields.
A message field is non-empty if HasField() would return true. A singular primitive field is non-empty if HasField() would return true in proto2 or it is non zero in proto3. A repeated field is non-empty if it contains at least one element. The fields are ordered by field number.
field descriptors and values for all fields in the message which are not empty. The values vary by field type.
Merges the contents of the specified message into current message.
This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and groups are recursively merged.
other_msg (Message) – A message to merge into the current message.
Merges serialized protocol buffer data into this message.
When we find a field in serialized that is already present in this message:
- If it’s a “repeated” field, we append to the end of our list.
- Else, if it’s a scalar, we overwrite our field.
- Else, (it’s a nonrepeated composite), we recursively merge into the existing composite.
serialized (bytes) – Any object that allows us to call memoryview(serialized) to access a string of bytes using the buffer interface.
The number of bytes read from serialized . For non-group messages, this will always be len(serialized) , but for messages which are actually groups, this will generally be less than len(serialized) , since we must stop when we reach an END_GROUP tag. Note that if we do stop because of an END_GROUP tag, the number of bytes returned does not include the bytes for the END_GROUP tag information.
Parse serialized protocol buffer data into this message.
Like MergeFromString() , except we clear the object first.
message.DecodeError if the input cannot be parsed. –
static RegisterExtension ( extension_handle ) ¶ SerializePartialToString ( **kwargs ) ¶
Serializes the protocol message to a binary string.
This method is similar to SerializeToString but doesn’t check if the message is initialized.
deterministic (bool) – If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.
A serialized representation of the partial message.
Serializes the protocol message to a binary string.
deterministic (bool) – If true, requests deterministic serialization of the protobuf, with predictable ordering of map keys.
A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized).
Mark this as present in the parent.
This normally happens automatically when you assign a field of a sub-message, but sometimes you want to make the sub-message present while keeping it empty. If you find yourself using this, you may want to reconsider your design.
Returns the UnknownFieldSet.
The unknown fields stored in this message.
Returns the name of the field that is set inside a oneof group.
If no field is set, returns None.
oneof_group (str) – the name of the oneof group to check.
The name of the group that is set, or None.
ValueError – no group with the given name exists
Table of Contents
- google.protobuf
- google.protobuf.any_pb2
- google.protobuf.descriptor
- google.protobuf.descriptor_database
- google.protobuf.descriptor_pb2
- google.protobuf.descriptor_pool
- google.protobuf.duration_pb2
- google.protobuf.empty_pb2
- google.protobuf.field_mask_pb2
- google.protobuf.internal.containers
- google.protobuf.json_format
- google.protobuf.message
- google.protobuf.message_factory
- google.protobuf.proto_builder
- google.protobuf.reflection
- google.protobuf.service
- google.protobuf.service_reflection
- google.protobuf.struct_pb2
- google.protobuf.symbol_database
- google.protobuf.text_encoding
- google.protobuf.text_format
- google.protobuf.timestamp_pb2
- google.protobuf.type_pb2
- google.protobuf.unknown_fields
- google.protobuf.wrappers_pb2
Related Topics
Fields¶
Fields are assigned using the Field class, instantiated within a Message declaration.
Fields always have a type (either a primitive, a message, or an enum) and a number .
import proto class Composer(proto.Message): given_name = proto.Field(proto.STRING, number=1) family_name = proto.Field(proto.STRING, number=2) class Song(proto.Message): composer = proto.Field(Composer, number=1) title = proto.Field(proto.STRING, number=2) lyrics = proto.Field(proto.STRING, number=3) year = proto.Field(proto.INT32, number=4)
For messages and enums, assign the message or enum class directly (as shown in the example above).
For messages declared in the same module, it is also possible to use a string with the message class’ name if the class is not yet declared, which allows for declaring messages out of order or with circular references.
Repeated fields¶
Some fields are actually repeated fields. In protocol buffers, repeated fields are generally equivalent to typed lists. In protocol buffers, these are declared using the repeated keyword:
message Album repeated Song songs = 1; string publisher = 2; >
Declare them in Python using the RepeatedField class:
class Album(proto.Message): songs = proto.RepeatedField(Song, number=1) publisher = proto.Field(proto.STRING, number=2)
Elements must be appended individually for repeated fields of struct.Value .
class Row(proto.Message): values = proto.RepeatedField(proto.MESSAGE, number=1, message=struct.Value,) >>> row = Row() >>> values = [struct_pb2.Value(string_value="hello")] >>> for v in values: >>> row.values.append(v)
Direct assignment will result in an error.
class Row(proto.Message): values = proto.RepeatedField(proto.MESSAGE, number=1, message=struct.Value,) >>> row = Row() >>> row.values = [struct_pb2.Value(string_value="hello")] Traceback (most recent call last): File "", line 1, in module> File "/usr/local/google/home/busunkim/github/python-automl/.nox/unit-3-8/lib/python3.8/site-packages/proto/message.py", line 543, in __setattr__ self._pb.MergeFrom(self._meta.pb(**key: pb_value>)) TypeError: Value must be iterable
Map fields¶
Similarly, some fields are map fields. In protocol buffers, map fields are equivalent to typed dictionaries, where the keys are either strings or integers, and the values can be any type. In protocol buffers, these use a special map syntax:
message Album mapuint32, Song> track_list = 1; string publisher = 2; >
Declare them in Python using the MapField class:
class Album(proto.Message): track_list = proto.MapField(proto.UINT32, Song, number=1) publisher = proto.Field(proto.STRING, number=2)
Oneofs (mutually-exclusive fields)¶
Protocol buffers allows certain fields to be declared as mutually exclusive. This is done by wrapping fields in a oneof syntax:
import "google/type/postal_address.proto"; message AlbumPurchase Album album = 1; oneof delivery google.type.PostalAddress postal_address = 2; string download_uri = 3; > >
When using this syntax, protocol buffers will enforce that only one of the given fields is set on the message, and setting a field within the oneof will clear any others.
Declare this in Python using the oneof keyword-argument, which takes a string (which should match for all fields within the oneof):
from google.type.postal_address import PostalAddress class AlbumPurchase(proto.Message): album = proto.Field(Album, number=1) postal_address = proto.Field(PostalAddress, number=2, oneof='delivery') download_uri = proto.Field(proto.STRING, number=3, oneof='delivery')
oneof fields must be declared consecutively, otherwise the C implementation of protocol buffers will reject the message. They need not have consecutive field numbers, but they must be declared in consecutive order.
If a message is constructed with multiple variants of a single oneof passed to its constructor, the last keyword/value pair passed will be the final value set.
This is consistent with PEP-468, which specifies the order that keyword args are seen by called functions, and with the regular protocol buffers runtime, which exhibits the same behavior.
import proto class Song(proto.Message): name = proto.Field(proto.STRING, number=1, oneof="identifier") database_id = proto.Field(proto.STRING, number=2, oneof="identifier") s = Song(name="Canon in D minor", database_id="b5a37aad3") assert "database_id" in s and "name" not in s s = Song(database_id="e6aa708c7e", name="Little Fugue") assert "name" in s and "database_id" not in s
Optional fields¶
All fields in protocol buffers are optional, but it is often necessary to check for field presence. Sometimes legitimate values for fields can be falsy, so checking for truthiness is not sufficient. Proto3 v3.12.0 added the optional keyword to field descriptions, which enables a mechanism for checking field presence.
In proto plus, fields can be marked as optional by passing optional=True in the constructor. The message class then gains a field of the same name that can be used to detect whether the field is present in message instances.
class Song(proto.Message): composer = proto.Field(Composer, number=1) title = proto.Field(proto.STRING, number=2) lyrics = proto.Field(proto.STRING, number=3) year = proto.Field(proto.INT32, number=4) performer = proto.Field(proto.STRING, number=5, optional=True) >>> s = Song( . composer='given_name': 'Johann', 'family_name': 'Pachelbel'>, . title='Canon in D', . year=1680, . genre=Genre.CLASSICAL, . ) >>> Song.performer in s False >>> s.performer = 'Brahms' >>> Song.performer in s True >>> del s.performer >>> Song.performer in s False >>> s.performer = "" # The mysterious, unnamed composer >>> Song.performer in s True
Under the hood, fields marked as optional are implemented via a synthetic one-variant oneof . See the protocolbuffers documentation for more information.
© Copyright 2018, Google LLC Revision 79ec8208 .
Versions latest stable v1.1.0 1.0.0 0.4.0 0.3.0 0.2.1 0.2.0 0.1.0 Downloads pdf html epub On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.