Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/google/protobuf/symbol_database.py: 47%
57 statements
« prev ^ index » next coverage.py v7.2.2, created at 2023-03-26 07:30 +0000
« prev ^ index » next coverage.py v7.2.2, created at 2023-03-26 07:30 +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"""A database of Python protocol buffer generated symbols.
33SymbolDatabase is the MessageFactory for messages generated at compile time,
34and makes it easy to create new instances of a registered type, given only the
35type's protocol buffer symbol name.
37Example usage::
39 db = symbol_database.SymbolDatabase()
41 # Register symbols of interest, from one or multiple files.
42 db.RegisterFileDescriptor(my_proto_pb2.DESCRIPTOR)
43 db.RegisterMessage(my_proto_pb2.MyMessage)
44 db.RegisterEnumDescriptor(my_proto_pb2.MyEnum.DESCRIPTOR)
46 # The database can be used as a MessageFactory, to generate types based on
47 # their name:
48 types = db.GetMessages(['my_proto.proto'])
49 my_message_instance = types['MyMessage']()
51 # The database's underlying descriptor pool can be queried, so it's not
52 # necessary to know a type's filename to be able to generate it:
53 filename = db.pool.FindFileContainingSymbol('MyMessage')
54 my_message_instance = db.GetMessages([filename])['MyMessage']()
56 # This functionality is also provided directly via a convenience method:
57 my_message_instance = db.GetSymbol('MyMessage')()
58"""
60import warnings
62from google.protobuf.internal import api_implementation
63from google.protobuf import descriptor_pool
64from google.protobuf import message_factory
67class SymbolDatabase():
68 """A database of Python generated symbols."""
70 # local cache of registered classes.
71 _classes = {}
73 def __init__(self, pool=None):
74 """Initializes a new SymbolDatabase."""
75 self.pool = pool or descriptor_pool.DescriptorPool()
77 def GetPrototype(self, descriptor):
78 warnings.warn('SymbolDatabase.GetPrototype() is deprecated. Please '
79 'use message_factory.GetMessageClass() instead. '
80 'SymbolDatabase.GetPrototype() will be removed soon.')
81 return message_factory.GetMessageClass(descriptor)
83 def CreatePrototype(self, descriptor):
84 warnings.warn('Directly call CreatePrototype() is wrong. Please use '
85 'message_factory.GetMessageClass() instead. '
86 'SymbolDatabase.CreatePrototype() will be removed soon.')
87 return message_factory._InternalCreateMessageClass(descriptor)
89 def GetMessages(self, files):
90 warnings.warn('SymbolDatabase.GetMessages() is deprecated. Please use '
91 'message_factory.GetMessageClassedForFiles() instead. '
92 'SymbolDatabase.GetMessages() will be removed soon.')
93 return message_factory.GetMessageClassedForFiles(files, self.pool)
95 def RegisterMessage(self, message):
96 """Registers the given message type in the local database.
98 Calls to GetSymbol() and GetMessages() will return messages registered here.
100 Args:
101 message: A :class:`google.protobuf.message.Message` subclass (or
102 instance); its descriptor will be registered.
104 Returns:
105 The provided message.
106 """
108 desc = message.DESCRIPTOR
109 self._classes[desc] = message
110 self.RegisterMessageDescriptor(desc)
111 return message
113 def RegisterMessageDescriptor(self, message_descriptor):
114 """Registers the given message descriptor in the local database.
116 Args:
117 message_descriptor (Descriptor): the message descriptor to add.
118 """
119 if api_implementation.Type() == 'python':
120 # pylint: disable=protected-access
121 self.pool._AddDescriptor(message_descriptor)
123 def RegisterEnumDescriptor(self, enum_descriptor):
124 """Registers the given enum descriptor in the local database.
126 Args:
127 enum_descriptor (EnumDescriptor): The enum descriptor to register.
129 Returns:
130 EnumDescriptor: The provided descriptor.
131 """
132 if api_implementation.Type() == 'python':
133 # pylint: disable=protected-access
134 self.pool._AddEnumDescriptor(enum_descriptor)
135 return enum_descriptor
137 def RegisterServiceDescriptor(self, service_descriptor):
138 """Registers the given service descriptor in the local database.
140 Args:
141 service_descriptor (ServiceDescriptor): the service descriptor to
142 register.
143 """
144 if api_implementation.Type() == 'python':
145 # pylint: disable=protected-access
146 self.pool._AddServiceDescriptor(service_descriptor)
148 def RegisterFileDescriptor(self, file_descriptor):
149 """Registers the given file descriptor in the local database.
151 Args:
152 file_descriptor (FileDescriptor): The file descriptor to register.
153 """
154 if api_implementation.Type() == 'python':
155 # pylint: disable=protected-access
156 self.pool._InternalAddFileDescriptor(file_descriptor)
158 def GetSymbol(self, symbol):
159 """Tries to find a symbol in the local database.
161 Currently, this method only returns message.Message instances, however, if
162 may be extended in future to support other symbol types.
164 Args:
165 symbol (str): a protocol buffer symbol.
167 Returns:
168 A Python class corresponding to the symbol.
170 Raises:
171 KeyError: if the symbol could not be found.
172 """
174 return self._classes[self.pool.FindMessageTypeByName(symbol)]
176 def GetMessages(self, files):
177 # TODO(amauryfa): Fix the differences with MessageFactory.
178 """Gets all registered messages from a specified file.
180 Only messages already created and registered will be returned; (this is the
181 case for imported _pb2 modules)
182 But unlike MessageFactory, this version also returns already defined nested
183 messages, but does not register any message extensions.
185 Args:
186 files (list[str]): The file names to extract messages from.
188 Returns:
189 A dictionary mapping proto names to the message classes.
191 Raises:
192 KeyError: if a file could not be found.
193 """
195 def _GetAllMessages(desc):
196 """Walk a message Descriptor and recursively yields all message names."""
197 yield desc
198 for msg_desc in desc.nested_types:
199 for nested_desc in _GetAllMessages(msg_desc):
200 yield nested_desc
202 result = {}
203 for file_name in files:
204 file_desc = self.pool.FindFileByName(file_name)
205 for msg_desc in file_desc.message_types_by_name.values():
206 for desc in _GetAllMessages(msg_desc):
207 try:
208 result[desc.full_name] = self._classes[desc]
209 except KeyError:
210 # This descriptor has no registered class, skip it.
211 pass
212 return result
215_DEFAULT = SymbolDatabase(pool=descriptor_pool.Default())
218def Default():
219 """Returns the default SymbolDatabase."""
220 return _DEFAULT