Path: blob/master/ invest-robot-contest_TinkoffBotTwitch-main/venv/lib/python3.8/site-packages/google/protobuf/message.py
7774 views
# Protocol Buffers - Google's data interchange format1# Copyright 2008 Google Inc. All rights reserved.2# https://developers.google.com/protocol-buffers/3#4# Redistribution and use in source and binary forms, with or without5# modification, are permitted provided that the following conditions are6# met:7#8# * Redistributions of source code must retain the above copyright9# notice, this list of conditions and the following disclaimer.10# * Redistributions in binary form must reproduce the above11# copyright notice, this list of conditions and the following disclaimer12# in the documentation and/or other materials provided with the13# distribution.14# * Neither the name of Google Inc. nor the names of its15# contributors may be used to endorse or promote products derived from16# this software without specific prior written permission.17#18# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS19# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT20# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR21# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT22# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,23# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT24# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,25# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY26# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT27# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE28# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.2930# TODO(robinson): We should just make these methods all "pure-virtual" and move31# all implementation out, into reflection.py for now.323334"""Contains an abstract base class for protocol messages."""3536__author__ = '[email protected] (Will Robinson)'3738class Error(Exception):39"""Base error type for this module."""40pass414243class DecodeError(Error):44"""Exception raised when deserializing messages."""45pass464748class EncodeError(Error):49"""Exception raised when serializing messages."""50pass515253class Message(object):5455"""Abstract base class for protocol messages.5657Protocol message classes are almost always generated by the protocol58compiler. These generated types subclass Message and implement the methods59shown below.60"""6162# TODO(robinson): Link to an HTML document here.6364# TODO(robinson): Document that instances of this class will also65# have an Extensions attribute with __getitem__ and __setitem__.66# Again, not sure how to best convey this.6768# TODO(robinson): Document that the class must also have a static69# RegisterExtension(extension_field) method.70# Not sure how to best express at this point.7172# TODO(robinson): Document these fields and methods.7374__slots__ = []7576#: The :class:`google.protobuf.descriptor.Descriptor` for this message type.77DESCRIPTOR = None7879def __deepcopy__(self, memo=None):80clone = type(self)()81clone.MergeFrom(self)82return clone8384def __eq__(self, other_msg):85"""Recursively compares two messages by value and structure."""86raise NotImplementedError8788def __ne__(self, other_msg):89# Can't just say self != other_msg, since that would infinitely recurse. :)90return not self == other_msg9192def __hash__(self):93raise TypeError('unhashable object')9495def __str__(self):96"""Outputs a human-readable representation of the message."""97raise NotImplementedError9899def __unicode__(self):100"""Outputs a human-readable representation of the message."""101raise NotImplementedError102103def MergeFrom(self, other_msg):104"""Merges the contents of the specified message into current message.105106This method merges the contents of the specified message into the current107message. Singular fields that are set in the specified message overwrite108the corresponding fields in the current message. Repeated fields are109appended. Singular sub-messages and groups are recursively merged.110111Args:112other_msg (Message): A message to merge into the current message.113"""114raise NotImplementedError115116def CopyFrom(self, other_msg):117"""Copies the content of the specified message into the current message.118119The method clears the current message and then merges the specified120message using MergeFrom.121122Args:123other_msg (Message): A message to copy into the current one.124"""125if self is other_msg:126return127self.Clear()128self.MergeFrom(other_msg)129130def Clear(self):131"""Clears all data that was set in the message."""132raise NotImplementedError133134def SetInParent(self):135"""Mark this as present in the parent.136137This normally happens automatically when you assign a field of a138sub-message, but sometimes you want to make the sub-message139present while keeping it empty. If you find yourself using this,140you may want to reconsider your design.141"""142raise NotImplementedError143144def IsInitialized(self):145"""Checks if the message is initialized.146147Returns:148bool: The method returns True if the message is initialized (i.e. all of149its required fields are set).150"""151raise NotImplementedError152153# TODO(robinson): MergeFromString() should probably return None and be154# implemented in terms of a helper that returns the # of bytes read. Our155# deserialization routines would use the helper when recursively156# deserializing, but the end user would almost always just want the no-return157# MergeFromString().158159def MergeFromString(self, serialized):160"""Merges serialized protocol buffer data into this message.161162When we find a field in `serialized` that is already present163in this message:164165- If it's a "repeated" field, we append to the end of our list.166- Else, if it's a scalar, we overwrite our field.167- Else, (it's a nonrepeated composite), we recursively merge168into the existing composite.169170Args:171serialized (bytes): Any object that allows us to call172``memoryview(serialized)`` to access a string of bytes using the173buffer interface.174175Returns:176int: The number of bytes read from `serialized`.177For non-group messages, this will always be `len(serialized)`,178but for messages which are actually groups, this will179generally be less than `len(serialized)`, since we must180stop when we reach an ``END_GROUP`` tag. Note that if181we *do* stop because of an ``END_GROUP`` tag, the number182of bytes returned does not include the bytes183for the ``END_GROUP`` tag information.184185Raises:186DecodeError: if the input cannot be parsed.187"""188# TODO(robinson): Document handling of unknown fields.189# TODO(robinson): When we switch to a helper, this will return None.190raise NotImplementedError191192def ParseFromString(self, serialized):193"""Parse serialized protocol buffer data into this message.194195Like :func:`MergeFromString()`, except we clear the object first.196197Raises:198message.DecodeError if the input cannot be parsed.199"""200self.Clear()201return self.MergeFromString(serialized)202203def SerializeToString(self, **kwargs):204"""Serializes the protocol message to a binary string.205206Keyword Args:207deterministic (bool): If true, requests deterministic serialization208of the protobuf, with predictable ordering of map keys.209210Returns:211A binary string representation of the message if all of the required212fields in the message are set (i.e. the message is initialized).213214Raises:215EncodeError: if the message isn't initialized (see :func:`IsInitialized`).216"""217raise NotImplementedError218219def SerializePartialToString(self, **kwargs):220"""Serializes the protocol message to a binary string.221222This method is similar to SerializeToString but doesn't check if the223message is initialized.224225Keyword Args:226deterministic (bool): If true, requests deterministic serialization227of the protobuf, with predictable ordering of map keys.228229Returns:230bytes: A serialized representation of the partial message.231"""232raise NotImplementedError233234# TODO(robinson): Decide whether we like these better235# than auto-generated has_foo() and clear_foo() methods236# on the instances themselves. This way is less consistent237# with C++, but it makes reflection-type access easier and238# reduces the number of magically autogenerated things.239#240# TODO(robinson): Be sure to document (and test) exactly241# which field names are accepted here. Are we case-sensitive?242# What do we do with fields that share names with Python keywords243# like 'lambda' and 'yield'?244#245# nnorwitz says:246# """247# Typically (in python), an underscore is appended to names that are248# keywords. So they would become lambda_ or yield_.249# """250def ListFields(self):251"""Returns a list of (FieldDescriptor, value) tuples for present fields.252253A message field is non-empty if HasField() would return true. A singular254primitive field is non-empty if HasField() would return true in proto2 or it255is non zero in proto3. A repeated field is non-empty if it contains at least256one element. The fields are ordered by field number.257258Returns:259list[tuple(FieldDescriptor, value)]: field descriptors and values260for all fields in the message which are not empty. The values vary by261field type.262"""263raise NotImplementedError264265def HasField(self, field_name):266"""Checks if a certain field is set for the message.267268For a oneof group, checks if any field inside is set. Note that if the269field_name is not defined in the message descriptor, :exc:`ValueError` will270be raised.271272Args:273field_name (str): The name of the field to check for presence.274275Returns:276bool: Whether a value has been set for the named field.277278Raises:279ValueError: if the `field_name` is not a member of this message.280"""281raise NotImplementedError282283def ClearField(self, field_name):284"""Clears the contents of a given field.285286Inside a oneof group, clears the field set. If the name neither refers to a287defined field or oneof group, :exc:`ValueError` is raised.288289Args:290field_name (str): The name of the field to check for presence.291292Raises:293ValueError: if the `field_name` is not a member of this message.294"""295raise NotImplementedError296297def WhichOneof(self, oneof_group):298"""Returns the name of the field that is set inside a oneof group.299300If no field is set, returns None.301302Args:303oneof_group (str): the name of the oneof group to check.304305Returns:306str or None: The name of the group that is set, or None.307308Raises:309ValueError: no group with the given name exists310"""311raise NotImplementedError312313def HasExtension(self, extension_handle):314"""Checks if a certain extension is present for this message.315316Extensions are retrieved using the :attr:`Extensions` mapping (if present).317318Args:319extension_handle: The handle for the extension to check.320321Returns:322bool: Whether the extension is present for this message.323324Raises:325KeyError: if the extension is repeated. Similar to repeated fields,326there is no separate notion of presence: a "not present" repeated327extension is an empty list.328"""329raise NotImplementedError330331def ClearExtension(self, extension_handle):332"""Clears the contents of a given extension.333334Args:335extension_handle: The handle for the extension to clear.336"""337raise NotImplementedError338339def UnknownFields(self):340"""Returns the UnknownFieldSet.341342Returns:343UnknownFieldSet: The unknown fields stored in this message.344"""345raise NotImplementedError346347def DiscardUnknownFields(self):348"""Clears all fields in the :class:`UnknownFieldSet`.349350This operation is recursive for nested message.351"""352raise NotImplementedError353354def ByteSize(self):355"""Returns the serialized size of this message.356357Recursively calls ByteSize() on all contained messages.358359Returns:360int: The number of bytes required to serialize this message.361"""362raise NotImplementedError363364@classmethod365def FromString(cls, s):366raise NotImplementedError367368@staticmethod369def RegisterExtension(extension_handle):370raise NotImplementedError371372def _SetListener(self, message_listener):373"""Internal method used by the protocol message implementation.374Clients should not call this directly.375376Sets a listener that this message will call on certain state transitions.377378The purpose of this method is to register back-edges from children to379parents at runtime, for the purpose of setting "has" bits and380byte-size-dirty bits in the parent and ancestor objects whenever a child or381descendant object is modified.382383If the client wants to disconnect this Message from the object tree, she384explicitly sets callback to None.385386If message_listener is None, unregisters any existing listener. Otherwise,387message_listener must implement the MessageListener interface in388internal/message_listener.py, and we discard any listener registered389via a previous _SetListener() call.390"""391raise NotImplementedError392393def __getstate__(self):394"""Support the pickle protocol."""395return dict(serialized=self.SerializePartialToString())396397def __setstate__(self, state):398"""Support the pickle protocol."""399self.__init__()400serialized = state['serialized']401# On Python 3, using encoding='latin1' is required for unpickling402# protos pickled by Python 2.403if not isinstance(serialized, bytes):404serialized = serialized.encode('latin1')405self.ParseFromString(serialized)406407def __reduce__(self):408message_descriptor = self.DESCRIPTOR409if message_descriptor.containing_type is None:410return type(self), (), self.__getstate__()411# the message type must be nested.412# Python does not pickle nested classes; use the symbol_database on the413# receiving end.414container = message_descriptor415return (_InternalConstructMessage, (container.full_name,),416self.__getstate__())417418419def _InternalConstructMessage(full_name):420"""Constructs a nested message."""421from google.protobuf import symbol_database # pylint:disable=g-import-not-at-top422423return symbol_database.Default().GetSymbol(full_name)()424425426