Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/google/protobuf/message.py: 49%
90 statements
« prev ^ index » next coverage.py v7.3.1, created at 2023-09-25 06:37 +0000
« prev ^ index » next coverage.py v7.3.1, created at 2023-09-25 06:37 +0000
1# Protocol Buffers - Google's data interchange format
2# Copyright 2008 Google Inc. All rights reserved.
3# https://developers.google.com/protocol-buffers/
4#
5# Redistribution and use in source and binary forms, with or without
6# modification, are permitted provided that the following conditions are
7# met:
8#
9# * Redistributions of source code must retain the above copyright
10# notice, this list of conditions and the following disclaimer.
11# * Redistributions in binary form must reproduce the above
12# copyright notice, this list of conditions and the following disclaimer
13# in the documentation and/or other materials provided with the
14# distribution.
15# * Neither the name of Google Inc. nor the names of its
16# contributors may be used to endorse or promote products derived from
17# this software without specific prior written permission.
18#
19# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31# TODO(robinson): We should just make these methods all "pure-virtual" and move
32# all implementation out, into reflection.py for now.
35"""Contains an abstract base class for protocol messages."""
37__author__ = 'robinson@google.com (Will Robinson)'
39class Error(Exception):
40 """Base error type for this module."""
41 pass
44class DecodeError(Error):
45 """Exception raised when deserializing messages."""
46 pass
49class EncodeError(Error):
50 """Exception raised when serializing messages."""
51 pass
54class Message(object):
56 """Abstract base class for protocol messages.
58 Protocol message classes are almost always generated by the protocol
59 compiler. These generated types subclass Message and implement the methods
60 shown below.
61 """
63 # TODO(robinson): Link to an HTML document here.
65 # TODO(robinson): Document that instances of this class will also
66 # have an Extensions attribute with __getitem__ and __setitem__.
67 # Again, not sure how to best convey this.
69 # TODO(robinson): Document these fields and methods.
71 __slots__ = []
73 #: The :class:`google.protobuf.Descriptor`
74 # for this message type.
75 DESCRIPTOR = None
77 def __deepcopy__(self, memo=None):
78 clone = type(self)()
79 clone.MergeFrom(self)
80 return clone
82 def __eq__(self, other_msg):
83 """Recursively compares two messages by value and structure."""
84 raise NotImplementedError
86 def __ne__(self, other_msg):
87 # Can't just say self != other_msg, since that would infinitely recurse. :)
88 return not self == other_msg
90 def __hash__(self):
91 raise TypeError('unhashable object')
93 def __str__(self):
94 """Outputs a human-readable representation of the message."""
95 raise NotImplementedError
97 def __unicode__(self):
98 """Outputs a human-readable representation of the message."""
99 raise NotImplementedError
101 def MergeFrom(self, other_msg):
102 """Merges the contents of the specified message into current message.
104 This method merges the contents of the specified message into the current
105 message. Singular fields that are set in the specified message overwrite
106 the corresponding fields in the current message. Repeated fields are
107 appended. Singular sub-messages and groups are recursively merged.
109 Args:
110 other_msg (Message): A message to merge into the current message.
111 """
112 raise NotImplementedError
114 def CopyFrom(self, other_msg):
115 """Copies the content of the specified message into the current message.
117 The method clears the current message and then merges the specified
118 message using MergeFrom.
120 Args:
121 other_msg (Message): A message to copy into the current one.
122 """
123 if self is other_msg:
124 return
125 self.Clear()
126 self.MergeFrom(other_msg)
128 def Clear(self):
129 """Clears all data that was set in the message."""
130 raise NotImplementedError
132 def SetInParent(self):
133 """Mark this as present in the parent.
135 This normally happens automatically when you assign a field of a
136 sub-message, but sometimes you want to make the sub-message
137 present while keeping it empty. If you find yourself using this,
138 you may want to reconsider your design.
139 """
140 raise NotImplementedError
142 def IsInitialized(self):
143 """Checks if the message is initialized.
145 Returns:
146 bool: The method returns True if the message is initialized (i.e. all of
147 its required fields are set).
148 """
149 raise NotImplementedError
151 # TODO(robinson): MergeFromString() should probably return None and be
152 # implemented in terms of a helper that returns the # of bytes read. Our
153 # deserialization routines would use the helper when recursively
154 # deserializing, but the end user would almost always just want the no-return
155 # MergeFromString().
157 def MergeFromString(self, serialized):
158 """Merges serialized protocol buffer data into this message.
160 When we find a field in `serialized` that is already present
161 in this message:
163 - If it's a "repeated" field, we append to the end of our list.
164 - Else, if it's a scalar, we overwrite our field.
165 - Else, (it's a nonrepeated composite), we recursively merge
166 into the existing composite.
168 Args:
169 serialized (bytes): Any object that allows us to call
170 ``memoryview(serialized)`` to access a string of bytes using the
171 buffer interface.
173 Returns:
174 int: The number of bytes read from `serialized`.
175 For non-group messages, this will always be `len(serialized)`,
176 but for messages which are actually groups, this will
177 generally be less than `len(serialized)`, since we must
178 stop when we reach an ``END_GROUP`` tag. Note that if
179 we *do* stop because of an ``END_GROUP`` tag, the number
180 of bytes returned does not include the bytes
181 for the ``END_GROUP`` tag information.
183 Raises:
184 DecodeError: if the input cannot be parsed.
185 """
186 # TODO(robinson): Document handling of unknown fields.
187 # TODO(robinson): When we switch to a helper, this will return None.
188 raise NotImplementedError
190 def ParseFromString(self, serialized):
191 """Parse serialized protocol buffer data in binary form into this message.
193 Like :func:`MergeFromString()`, except we clear the object first.
195 Raises:
196 message.DecodeError if the input cannot be parsed.
197 """
198 self.Clear()
199 return self.MergeFromString(serialized)
201 def SerializeToString(self, **kwargs):
202 """Serializes the protocol message to a binary string.
204 Keyword Args:
205 deterministic (bool): If true, requests deterministic serialization
206 of the protobuf, with predictable ordering of map keys.
208 Returns:
209 A binary string representation of the message if all of the required
210 fields in the message are set (i.e. the message is initialized).
212 Raises:
213 EncodeError: if the message isn't initialized (see :func:`IsInitialized`).
214 """
215 raise NotImplementedError
217 def SerializePartialToString(self, **kwargs):
218 """Serializes the protocol message to a binary string.
220 This method is similar to SerializeToString but doesn't check if the
221 message is initialized.
223 Keyword Args:
224 deterministic (bool): If true, requests deterministic serialization
225 of the protobuf, with predictable ordering of map keys.
227 Returns:
228 bytes: A serialized representation of the partial message.
229 """
230 raise NotImplementedError
232 # TODO(robinson): Decide whether we like these better
233 # than auto-generated has_foo() and clear_foo() methods
234 # on the instances themselves. This way is less consistent
235 # with C++, but it makes reflection-type access easier and
236 # reduces the number of magically autogenerated things.
237 #
238 # TODO(robinson): Be sure to document (and test) exactly
239 # which field names are accepted here. Are we case-sensitive?
240 # What do we do with fields that share names with Python keywords
241 # like 'lambda' and 'yield'?
242 #
243 # nnorwitz says:
244 # """
245 # Typically (in python), an underscore is appended to names that are
246 # keywords. So they would become lambda_ or yield_.
247 # """
248 def ListFields(self):
249 """Returns a list of (FieldDescriptor, value) tuples for present fields.
251 A message field is non-empty if HasField() would return true. A singular
252 primitive field is non-empty if HasField() would return true in proto2 or it
253 is non zero in proto3. A repeated field is non-empty if it contains at least
254 one element. The fields are ordered by field number.
256 Returns:
257 list[tuple(FieldDescriptor, value)]: field descriptors and values
258 for all fields in the message which are not empty. The values vary by
259 field type.
260 """
261 raise NotImplementedError
263 def HasField(self, field_name):
264 """Checks if a certain field is set for the message.
266 For a oneof group, checks if any field inside is set. Note that if the
267 field_name is not defined in the message descriptor, :exc:`ValueError` will
268 be raised.
270 Args:
271 field_name (str): The name of the field to check for presence.
273 Returns:
274 bool: Whether a value has been set for the named field.
276 Raises:
277 ValueError: if the `field_name` is not a member of this message.
278 """
279 raise NotImplementedError
281 def ClearField(self, field_name):
282 """Clears the contents of a given field.
284 Inside a oneof group, clears the field set. If the name neither refers to a
285 defined field or oneof group, :exc:`ValueError` is raised.
287 Args:
288 field_name (str): The name of the field to check for presence.
290 Raises:
291 ValueError: if the `field_name` is not a member of this message.
292 """
293 raise NotImplementedError
295 def WhichOneof(self, oneof_group):
296 """Returns the name of the field that is set inside a oneof group.
298 If no field is set, returns None.
300 Args:
301 oneof_group (str): the name of the oneof group to check.
303 Returns:
304 str or None: The name of the group that is set, or None.
306 Raises:
307 ValueError: no group with the given name exists
308 """
309 raise NotImplementedError
311 def HasExtension(self, field_descriptor):
312 """Checks if a certain extension is present for this message.
314 Extensions are retrieved using the :attr:`Extensions` mapping (if present).
316 Args:
317 field_descriptor: The field descriptor for the extension to check.
319 Returns:
320 bool: Whether the extension is present for this message.
322 Raises:
323 KeyError: if the extension is repeated. Similar to repeated fields,
324 there is no separate notion of presence: a "not present" repeated
325 extension is an empty list.
326 """
327 raise NotImplementedError
329 def ClearExtension(self, field_descriptor):
330 """Clears the contents of a given extension.
332 Args:
333 field_descriptor: The field descriptor for the extension to clear.
334 """
335 raise NotImplementedError
337 def UnknownFields(self):
338 """Returns the UnknownFieldSet.
340 Returns:
341 UnknownFieldSet: The unknown fields stored in this message.
342 """
343 raise NotImplementedError
345 def DiscardUnknownFields(self):
346 """Clears all fields in the :class:`UnknownFieldSet`.
348 This operation is recursive for nested message.
349 """
350 raise NotImplementedError
352 def ByteSize(self):
353 """Returns the serialized size of this message.
355 Recursively calls ByteSize() on all contained messages.
357 Returns:
358 int: The number of bytes required to serialize this message.
359 """
360 raise NotImplementedError
362 @classmethod
363 def FromString(cls, s):
364 raise NotImplementedError
366# TODO(b/286557203): Remove it in OSS
367 @staticmethod
368 def RegisterExtension(field_descriptor):
369 raise NotImplementedError
371 def _SetListener(self, message_listener):
372 """Internal method used by the protocol message implementation.
373 Clients should not call this directly.
375 Sets a listener that this message will call on certain state transitions.
377 The purpose of this method is to register back-edges from children to
378 parents at runtime, for the purpose of setting "has" bits and
379 byte-size-dirty bits in the parent and ancestor objects whenever a child or
380 descendant object is modified.
382 If the client wants to disconnect this Message from the object tree, she
383 explicitly sets callback to None.
385 If message_listener is None, unregisters any existing listener. Otherwise,
386 message_listener must implement the MessageListener interface in
387 internal/message_listener.py, and we discard any listener registered
388 via a previous _SetListener() call.
389 """
390 raise NotImplementedError
392 def __getstate__(self):
393 """Support the pickle protocol."""
394 return dict(serialized=self.SerializePartialToString())
396 def __setstate__(self, state):
397 """Support the pickle protocol."""
398 self.__init__()
399 serialized = state['serialized']
400 # On Python 3, using encoding='latin1' is required for unpickling
401 # protos pickled by Python 2.
402 if not isinstance(serialized, bytes):
403 serialized = serialized.encode('latin1')
404 self.ParseFromString(serialized)
406 def __reduce__(self):
407 message_descriptor = self.DESCRIPTOR
408 if message_descriptor.containing_type is None:
409 return type(self), (), self.__getstate__()
410 # the message type must be nested.
411 # Python does not pickle nested classes; use the symbol_database on the
412 # receiving end.
413 container = message_descriptor
414 return (_InternalConstructMessage, (container.full_name,),
415 self.__getstate__())
418def _InternalConstructMessage(full_name):
419 """Constructs a nested message."""
420 from google.protobuf import symbol_database # pylint:disable=g-import-not-at-top
422 return symbol_database.Default().GetSymbol(full_name)()