Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/google/protobuf/internal/extension_dict.py: 22%
77 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:57 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:57 +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"""Contains _ExtensionDict class to represent extensions.
32"""
34from google.protobuf.internal import type_checkers
35from google.protobuf.descriptor import FieldDescriptor
38def _VerifyExtensionHandle(message, extension_handle):
39 """Verify that the given extension handle is valid."""
41 if not isinstance(extension_handle, FieldDescriptor):
42 raise KeyError('HasExtension() expects an extension handle, got: %s' %
43 extension_handle)
45 if not extension_handle.is_extension:
46 raise KeyError('"%s" is not an extension.' % extension_handle.full_name)
48 if not extension_handle.containing_type:
49 raise KeyError('"%s" is missing a containing_type.'
50 % extension_handle.full_name)
52 if extension_handle.containing_type is not message.DESCRIPTOR:
53 raise KeyError('Extension "%s" extends message type "%s", but this '
54 'message is of type "%s".' %
55 (extension_handle.full_name,
56 extension_handle.containing_type.full_name,
57 message.DESCRIPTOR.full_name))
60# TODO(robinson): Unify error handling of "unknown extension" crap.
61# TODO(robinson): Support iteritems()-style iteration over all
62# extensions with the "has" bits turned on?
63class _ExtensionDict(object):
65 """Dict-like container for Extension fields on proto instances.
67 Note that in all cases we expect extension handles to be
68 FieldDescriptors.
69 """
71 def __init__(self, extended_message):
72 """
73 Args:
74 extended_message: Message instance for which we are the Extensions dict.
75 """
76 self._extended_message = extended_message
78 def __getitem__(self, extension_handle):
79 """Returns the current value of the given extension handle."""
81 _VerifyExtensionHandle(self._extended_message, extension_handle)
83 result = self._extended_message._fields.get(extension_handle)
84 if result is not None:
85 return result
87 if extension_handle.label == FieldDescriptor.LABEL_REPEATED:
88 result = extension_handle._default_constructor(self._extended_message)
89 elif extension_handle.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE:
90 message_type = extension_handle.message_type
91 if not hasattr(message_type, '_concrete_class'):
92 # pylint: disable=g-import-not-at-top
93 from google.protobuf import message_factory
94 message_factory.GetMessageClass(message_type)
95 assert getattr(extension_handle.message_type, '_concrete_class', None), (
96 'Uninitialized concrete class found for field %r (message type %r)'
97 % (extension_handle.full_name,
98 extension_handle.message_type.full_name))
99 result = extension_handle.message_type._concrete_class()
100 try:
101 result._SetListener(self._extended_message._listener_for_children)
102 except ReferenceError:
103 pass
104 else:
105 # Singular scalar -- just return the default without inserting into the
106 # dict.
107 return extension_handle.default_value
109 # Atomically check if another thread has preempted us and, if not, swap
110 # in the new object we just created. If someone has preempted us, we
111 # take that object and discard ours.
112 # WARNING: We are relying on setdefault() being atomic. This is true
113 # in CPython but we haven't investigated others. This warning appears
114 # in several other locations in this file.
115 result = self._extended_message._fields.setdefault(
116 extension_handle, result)
118 return result
120 def __eq__(self, other):
121 if not isinstance(other, self.__class__):
122 return False
124 my_fields = self._extended_message.ListFields()
125 other_fields = other._extended_message.ListFields()
127 # Get rid of non-extension fields.
128 my_fields = [field for field in my_fields if field.is_extension]
129 other_fields = [field for field in other_fields if field.is_extension]
131 return my_fields == other_fields
133 def __ne__(self, other):
134 return not self == other
136 def __len__(self):
137 fields = self._extended_message.ListFields()
138 # Get rid of non-extension fields.
139 extension_fields = [field for field in fields if field[0].is_extension]
140 return len(extension_fields)
142 def __hash__(self):
143 raise TypeError('unhashable object')
145 # Note that this is only meaningful for non-repeated, scalar extension
146 # fields. Note also that we may have to call _Modified() when we do
147 # successfully set a field this way, to set any necessary "has" bits in the
148 # ancestors of the extended message.
149 def __setitem__(self, extension_handle, value):
150 """If extension_handle specifies a non-repeated, scalar extension
151 field, sets the value of that field.
152 """
154 _VerifyExtensionHandle(self._extended_message, extension_handle)
156 if (extension_handle.label == FieldDescriptor.LABEL_REPEATED or
157 extension_handle.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE):
158 raise TypeError(
159 'Cannot assign to extension "%s" because it is a repeated or '
160 'composite type.' % extension_handle.full_name)
162 # It's slightly wasteful to lookup the type checker each time,
163 # but we expect this to be a vanishingly uncommon case anyway.
164 type_checker = type_checkers.GetTypeChecker(extension_handle)
165 # pylint: disable=protected-access
166 self._extended_message._fields[extension_handle] = (
167 type_checker.CheckValue(value))
168 self._extended_message._Modified()
170 def __delitem__(self, extension_handle):
171 self._extended_message.ClearExtension(extension_handle)
173 def _FindExtensionByName(self, name):
174 """Tries to find a known extension with the specified name.
176 Args:
177 name: Extension full name.
179 Returns:
180 Extension field descriptor.
181 """
182 return self._extended_message._extensions_by_name.get(name, None)
184 def _FindExtensionByNumber(self, number):
185 """Tries to find a known extension with the field number.
187 Args:
188 number: Extension field number.
190 Returns:
191 Extension field descriptor.
192 """
193 return self._extended_message._extensions_by_number.get(number, None)
195 def __iter__(self):
196 # Return a generator over the populated extension fields
197 return (f[0] for f in self._extended_message.ListFields()
198 if f[0].is_extension)
200 def __contains__(self, extension_handle):
201 _VerifyExtensionHandle(self._extended_message, extension_handle)
203 if extension_handle not in self._extended_message._fields:
204 return False
206 if extension_handle.label == FieldDescriptor.LABEL_REPEATED:
207 return bool(self._extended_message._fields.get(extension_handle))
209 if extension_handle.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE:
210 value = self._extended_message._fields.get(extension_handle)
211 # pylint: disable=protected-access
212 return value is not None and value._is_present_in_parent
214 return True