店播爬取Python脚本

descriptor_pool.py 45KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272
  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.
  30. """Provides DescriptorPool to use as a container for proto2 descriptors.
  31. The DescriptorPool is used in conjection with a DescriptorDatabase to maintain
  32. a collection of protocol buffer descriptors for use when dynamically creating
  33. message types at runtime.
  34. For most applications protocol buffers should be used via modules generated by
  35. the protocol buffer compiler tool. This should only be used when the type of
  36. protocol buffers used in an application or library cannot be predetermined.
  37. Below is a straightforward example on how to use this class::
  38. pool = DescriptorPool()
  39. file_descriptor_protos = [ ... ]
  40. for file_descriptor_proto in file_descriptor_protos:
  41. pool.Add(file_descriptor_proto)
  42. my_message_descriptor = pool.FindMessageTypeByName('some.package.MessageType')
  43. The message descriptor can be used in conjunction with the message_factory
  44. module in order to create a protocol buffer class that can be encoded and
  45. decoded.
  46. If you want to get a Python class for the specified proto, use the
  47. helper functions inside google.protobuf.message_factory
  48. directly instead of this class.
  49. """
  50. __author__ = 'matthewtoia@google.com (Matt Toia)'
  51. import collections
  52. import warnings
  53. from google.protobuf import descriptor
  54. from google.protobuf import descriptor_database
  55. from google.protobuf import text_encoding
  56. _USE_C_DESCRIPTORS = descriptor._USE_C_DESCRIPTORS # pylint: disable=protected-access
  57. def _Deprecated(func):
  58. """Mark functions as deprecated."""
  59. def NewFunc(*args, **kwargs):
  60. warnings.warn(
  61. 'Call to deprecated function %s(). Note: Do add unlinked descriptors '
  62. 'to descriptor_pool is wrong. Use Add() or AddSerializedFile() '
  63. 'instead.' % func.__name__,
  64. category=DeprecationWarning)
  65. return func(*args, **kwargs)
  66. NewFunc.__name__ = func.__name__
  67. NewFunc.__doc__ = func.__doc__
  68. NewFunc.__dict__.update(func.__dict__)
  69. return NewFunc
  70. def _NormalizeFullyQualifiedName(name):
  71. """Remove leading period from fully-qualified type name.
  72. Due to b/13860351 in descriptor_database.py, types in the root namespace are
  73. generated with a leading period. This function removes that prefix.
  74. Args:
  75. name (str): The fully-qualified symbol name.
  76. Returns:
  77. str: The normalized fully-qualified symbol name.
  78. """
  79. return name.lstrip('.')
  80. def _OptionsOrNone(descriptor_proto):
  81. """Returns the value of the field `options`, or None if it is not set."""
  82. if descriptor_proto.HasField('options'):
  83. return descriptor_proto.options
  84. else:
  85. return None
  86. def _IsMessageSetExtension(field):
  87. return (field.is_extension and
  88. field.containing_type.has_options and
  89. field.containing_type.GetOptions().message_set_wire_format and
  90. field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and
  91. field.label == descriptor.FieldDescriptor.LABEL_OPTIONAL)
  92. class DescriptorPool(object):
  93. """A collection of protobufs dynamically constructed by descriptor protos."""
  94. if _USE_C_DESCRIPTORS:
  95. def __new__(cls, descriptor_db=None):
  96. # pylint: disable=protected-access
  97. return descriptor._message.DescriptorPool(descriptor_db)
  98. def __init__(self, descriptor_db=None):
  99. """Initializes a Pool of proto buffs.
  100. The descriptor_db argument to the constructor is provided to allow
  101. specialized file descriptor proto lookup code to be triggered on demand. An
  102. example would be an implementation which will read and compile a file
  103. specified in a call to FindFileByName() and not require the call to Add()
  104. at all. Results from this database will be cached internally here as well.
  105. Args:
  106. descriptor_db: A secondary source of file descriptors.
  107. """
  108. self._internal_db = descriptor_database.DescriptorDatabase()
  109. self._descriptor_db = descriptor_db
  110. self._descriptors = {}
  111. self._enum_descriptors = {}
  112. self._service_descriptors = {}
  113. self._file_descriptors = {}
  114. self._toplevel_extensions = {}
  115. # TODO(jieluo): Remove _file_desc_by_toplevel_extension after
  116. # maybe year 2020 for compatibility issue (with 3.4.1 only).
  117. self._file_desc_by_toplevel_extension = {}
  118. self._top_enum_values = {}
  119. # We store extensions in two two-level mappings: The first key is the
  120. # descriptor of the message being extended, the second key is the extension
  121. # full name or its tag number.
  122. self._extensions_by_name = collections.defaultdict(dict)
  123. self._extensions_by_number = collections.defaultdict(dict)
  124. def _CheckConflictRegister(self, desc, desc_name, file_name):
  125. """Check if the descriptor name conflicts with another of the same name.
  126. Args:
  127. desc: Descriptor of a message, enum, service, extension or enum value.
  128. desc_name (str): the full name of desc.
  129. file_name (str): The file name of descriptor.
  130. """
  131. for register, descriptor_type in [
  132. (self._descriptors, descriptor.Descriptor),
  133. (self._enum_descriptors, descriptor.EnumDescriptor),
  134. (self._service_descriptors, descriptor.ServiceDescriptor),
  135. (self._toplevel_extensions, descriptor.FieldDescriptor),
  136. (self._top_enum_values, descriptor.EnumValueDescriptor)]:
  137. if desc_name in register:
  138. old_desc = register[desc_name]
  139. if isinstance(old_desc, descriptor.EnumValueDescriptor):
  140. old_file = old_desc.type.file.name
  141. else:
  142. old_file = old_desc.file.name
  143. if not isinstance(desc, descriptor_type) or (
  144. old_file != file_name):
  145. error_msg = ('Conflict register for file "' + file_name +
  146. '": ' + desc_name +
  147. ' is already defined in file "' +
  148. old_file + '". Please fix the conflict by adding '
  149. 'package name on the proto file, or use different '
  150. 'name for the duplication.')
  151. if isinstance(desc, descriptor.EnumValueDescriptor):
  152. error_msg += ('\nNote: enum values appear as '
  153. 'siblings of the enum type instead of '
  154. 'children of it.')
  155. raise TypeError(error_msg)
  156. return
  157. def Add(self, file_desc_proto):
  158. """Adds the FileDescriptorProto and its types to this pool.
  159. Args:
  160. file_desc_proto (FileDescriptorProto): The file descriptor to add.
  161. """
  162. self._internal_db.Add(file_desc_proto)
  163. def AddSerializedFile(self, serialized_file_desc_proto):
  164. """Adds the FileDescriptorProto and its types to this pool.
  165. Args:
  166. serialized_file_desc_proto (bytes): A bytes string, serialization of the
  167. :class:`FileDescriptorProto` to add.
  168. """
  169. # pylint: disable=g-import-not-at-top
  170. from google.protobuf import descriptor_pb2
  171. file_desc_proto = descriptor_pb2.FileDescriptorProto.FromString(
  172. serialized_file_desc_proto)
  173. self.Add(file_desc_proto)
  174. # Add Descriptor to descriptor pool is dreprecated. Please use Add()
  175. # or AddSerializedFile() to add a FileDescriptorProto instead.
  176. @_Deprecated
  177. def AddDescriptor(self, desc):
  178. self._AddDescriptor(desc)
  179. # Never call this method. It is for internal usage only.
  180. def _AddDescriptor(self, desc):
  181. """Adds a Descriptor to the pool, non-recursively.
  182. If the Descriptor contains nested messages or enums, the caller must
  183. explicitly register them. This method also registers the FileDescriptor
  184. associated with the message.
  185. Args:
  186. desc: A Descriptor.
  187. """
  188. if not isinstance(desc, descriptor.Descriptor):
  189. raise TypeError('Expected instance of descriptor.Descriptor.')
  190. self._CheckConflictRegister(desc, desc.full_name, desc.file.name)
  191. self._descriptors[desc.full_name] = desc
  192. self._AddFileDescriptor(desc.file)
  193. # Add EnumDescriptor to descriptor pool is dreprecated. Please use Add()
  194. # or AddSerializedFile() to add a FileDescriptorProto instead.
  195. @_Deprecated
  196. def AddEnumDescriptor(self, enum_desc):
  197. self._AddEnumDescriptor(enum_desc)
  198. # Never call this method. It is for internal usage only.
  199. def _AddEnumDescriptor(self, enum_desc):
  200. """Adds an EnumDescriptor to the pool.
  201. This method also registers the FileDescriptor associated with the enum.
  202. Args:
  203. enum_desc: An EnumDescriptor.
  204. """
  205. if not isinstance(enum_desc, descriptor.EnumDescriptor):
  206. raise TypeError('Expected instance of descriptor.EnumDescriptor.')
  207. file_name = enum_desc.file.name
  208. self._CheckConflictRegister(enum_desc, enum_desc.full_name, file_name)
  209. self._enum_descriptors[enum_desc.full_name] = enum_desc
  210. # Top enum values need to be indexed.
  211. # Count the number of dots to see whether the enum is toplevel or nested
  212. # in a message. We cannot use enum_desc.containing_type at this stage.
  213. if enum_desc.file.package:
  214. top_level = (enum_desc.full_name.count('.')
  215. - enum_desc.file.package.count('.') == 1)
  216. else:
  217. top_level = enum_desc.full_name.count('.') == 0
  218. if top_level:
  219. file_name = enum_desc.file.name
  220. package = enum_desc.file.package
  221. for enum_value in enum_desc.values:
  222. full_name = _NormalizeFullyQualifiedName(
  223. '.'.join((package, enum_value.name)))
  224. self._CheckConflictRegister(enum_value, full_name, file_name)
  225. self._top_enum_values[full_name] = enum_value
  226. self._AddFileDescriptor(enum_desc.file)
  227. # Add ServiceDescriptor to descriptor pool is dreprecated. Please use Add()
  228. # or AddSerializedFile() to add a FileDescriptorProto instead.
  229. @_Deprecated
  230. def AddServiceDescriptor(self, service_desc):
  231. self._AddServiceDescriptor(service_desc)
  232. # Never call this method. It is for internal usage only.
  233. def _AddServiceDescriptor(self, service_desc):
  234. """Adds a ServiceDescriptor to the pool.
  235. Args:
  236. service_desc: A ServiceDescriptor.
  237. """
  238. if not isinstance(service_desc, descriptor.ServiceDescriptor):
  239. raise TypeError('Expected instance of descriptor.ServiceDescriptor.')
  240. self._CheckConflictRegister(service_desc, service_desc.full_name,
  241. service_desc.file.name)
  242. self._service_descriptors[service_desc.full_name] = service_desc
  243. # Add ExtensionDescriptor to descriptor pool is dreprecated. Please use Add()
  244. # or AddSerializedFile() to add a FileDescriptorProto instead.
  245. @_Deprecated
  246. def AddExtensionDescriptor(self, extension):
  247. self._AddExtensionDescriptor(extension)
  248. # Never call this method. It is for internal usage only.
  249. def _AddExtensionDescriptor(self, extension):
  250. """Adds a FieldDescriptor describing an extension to the pool.
  251. Args:
  252. extension: A FieldDescriptor.
  253. Raises:
  254. AssertionError: when another extension with the same number extends the
  255. same message.
  256. TypeError: when the specified extension is not a
  257. descriptor.FieldDescriptor.
  258. """
  259. if not (isinstance(extension, descriptor.FieldDescriptor) and
  260. extension.is_extension):
  261. raise TypeError('Expected an extension descriptor.')
  262. if extension.extension_scope is None:
  263. self._toplevel_extensions[extension.full_name] = extension
  264. try:
  265. existing_desc = self._extensions_by_number[
  266. extension.containing_type][extension.number]
  267. except KeyError:
  268. pass
  269. else:
  270. if extension is not existing_desc:
  271. raise AssertionError(
  272. 'Extensions "%s" and "%s" both try to extend message type "%s" '
  273. 'with field number %d.' %
  274. (extension.full_name, existing_desc.full_name,
  275. extension.containing_type.full_name, extension.number))
  276. self._extensions_by_number[extension.containing_type][
  277. extension.number] = extension
  278. self._extensions_by_name[extension.containing_type][
  279. extension.full_name] = extension
  280. # Also register MessageSet extensions with the type name.
  281. if _IsMessageSetExtension(extension):
  282. self._extensions_by_name[extension.containing_type][
  283. extension.message_type.full_name] = extension
  284. @_Deprecated
  285. def AddFileDescriptor(self, file_desc):
  286. self._InternalAddFileDescriptor(file_desc)
  287. # Never call this method. It is for internal usage only.
  288. def _InternalAddFileDescriptor(self, file_desc):
  289. """Adds a FileDescriptor to the pool, non-recursively.
  290. If the FileDescriptor contains messages or enums, the caller must explicitly
  291. register them.
  292. Args:
  293. file_desc: A FileDescriptor.
  294. """
  295. self._AddFileDescriptor(file_desc)
  296. # TODO(jieluo): This is a temporary solution for FieldDescriptor.file.
  297. # FieldDescriptor.file is added in code gen. Remove this solution after
  298. # maybe 2020 for compatibility reason (with 3.4.1 only).
  299. for extension in file_desc.extensions_by_name.values():
  300. self._file_desc_by_toplevel_extension[
  301. extension.full_name] = file_desc
  302. def _AddFileDescriptor(self, file_desc):
  303. """Adds a FileDescriptor to the pool, non-recursively.
  304. If the FileDescriptor contains messages or enums, the caller must explicitly
  305. register them.
  306. Args:
  307. file_desc: A FileDescriptor.
  308. """
  309. if not isinstance(file_desc, descriptor.FileDescriptor):
  310. raise TypeError('Expected instance of descriptor.FileDescriptor.')
  311. self._file_descriptors[file_desc.name] = file_desc
  312. def FindFileByName(self, file_name):
  313. """Gets a FileDescriptor by file name.
  314. Args:
  315. file_name (str): The path to the file to get a descriptor for.
  316. Returns:
  317. FileDescriptor: The descriptor for the named file.
  318. Raises:
  319. KeyError: if the file cannot be found in the pool.
  320. """
  321. try:
  322. return self._file_descriptors[file_name]
  323. except KeyError:
  324. pass
  325. try:
  326. file_proto = self._internal_db.FindFileByName(file_name)
  327. except KeyError as error:
  328. if self._descriptor_db:
  329. file_proto = self._descriptor_db.FindFileByName(file_name)
  330. else:
  331. raise error
  332. if not file_proto:
  333. raise KeyError('Cannot find a file named %s' % file_name)
  334. return self._ConvertFileProtoToFileDescriptor(file_proto)
  335. def FindFileContainingSymbol(self, symbol):
  336. """Gets the FileDescriptor for the file containing the specified symbol.
  337. Args:
  338. symbol (str): The name of the symbol to search for.
  339. Returns:
  340. FileDescriptor: Descriptor for the file that contains the specified
  341. symbol.
  342. Raises:
  343. KeyError: if the file cannot be found in the pool.
  344. """
  345. symbol = _NormalizeFullyQualifiedName(symbol)
  346. try:
  347. return self._InternalFindFileContainingSymbol(symbol)
  348. except KeyError:
  349. pass
  350. try:
  351. # Try fallback database. Build and find again if possible.
  352. self._FindFileContainingSymbolInDb(symbol)
  353. return self._InternalFindFileContainingSymbol(symbol)
  354. except KeyError:
  355. raise KeyError('Cannot find a file containing %s' % symbol)
  356. def _InternalFindFileContainingSymbol(self, symbol):
  357. """Gets the already built FileDescriptor containing the specified symbol.
  358. Args:
  359. symbol (str): The name of the symbol to search for.
  360. Returns:
  361. FileDescriptor: Descriptor for the file that contains the specified
  362. symbol.
  363. Raises:
  364. KeyError: if the file cannot be found in the pool.
  365. """
  366. try:
  367. return self._descriptors[symbol].file
  368. except KeyError:
  369. pass
  370. try:
  371. return self._enum_descriptors[symbol].file
  372. except KeyError:
  373. pass
  374. try:
  375. return self._service_descriptors[symbol].file
  376. except KeyError:
  377. pass
  378. try:
  379. return self._top_enum_values[symbol].type.file
  380. except KeyError:
  381. pass
  382. try:
  383. return self._file_desc_by_toplevel_extension[symbol]
  384. except KeyError:
  385. pass
  386. # Try fields, enum values and nested extensions inside a message.
  387. top_name, _, sub_name = symbol.rpartition('.')
  388. try:
  389. message = self.FindMessageTypeByName(top_name)
  390. assert (sub_name in message.extensions_by_name or
  391. sub_name in message.fields_by_name or
  392. sub_name in message.enum_values_by_name)
  393. return message.file
  394. except (KeyError, AssertionError):
  395. raise KeyError('Cannot find a file containing %s' % symbol)
  396. def FindMessageTypeByName(self, full_name):
  397. """Loads the named descriptor from the pool.
  398. Args:
  399. full_name (str): The full name of the descriptor to load.
  400. Returns:
  401. Descriptor: The descriptor for the named type.
  402. Raises:
  403. KeyError: if the message cannot be found in the pool.
  404. """
  405. full_name = _NormalizeFullyQualifiedName(full_name)
  406. if full_name not in self._descriptors:
  407. self._FindFileContainingSymbolInDb(full_name)
  408. return self._descriptors[full_name]
  409. def FindEnumTypeByName(self, full_name):
  410. """Loads the named enum descriptor from the pool.
  411. Args:
  412. full_name (str): The full name of the enum descriptor to load.
  413. Returns:
  414. EnumDescriptor: The enum descriptor for the named type.
  415. Raises:
  416. KeyError: if the enum cannot be found in the pool.
  417. """
  418. full_name = _NormalizeFullyQualifiedName(full_name)
  419. if full_name not in self._enum_descriptors:
  420. self._FindFileContainingSymbolInDb(full_name)
  421. return self._enum_descriptors[full_name]
  422. def FindFieldByName(self, full_name):
  423. """Loads the named field descriptor from the pool.
  424. Args:
  425. full_name (str): The full name of the field descriptor to load.
  426. Returns:
  427. FieldDescriptor: The field descriptor for the named field.
  428. Raises:
  429. KeyError: if the field cannot be found in the pool.
  430. """
  431. full_name = _NormalizeFullyQualifiedName(full_name)
  432. message_name, _, field_name = full_name.rpartition('.')
  433. message_descriptor = self.FindMessageTypeByName(message_name)
  434. return message_descriptor.fields_by_name[field_name]
  435. def FindOneofByName(self, full_name):
  436. """Loads the named oneof descriptor from the pool.
  437. Args:
  438. full_name (str): The full name of the oneof descriptor to load.
  439. Returns:
  440. OneofDescriptor: The oneof descriptor for the named oneof.
  441. Raises:
  442. KeyError: if the oneof cannot be found in the pool.
  443. """
  444. full_name = _NormalizeFullyQualifiedName(full_name)
  445. message_name, _, oneof_name = full_name.rpartition('.')
  446. message_descriptor = self.FindMessageTypeByName(message_name)
  447. return message_descriptor.oneofs_by_name[oneof_name]
  448. def FindExtensionByName(self, full_name):
  449. """Loads the named extension descriptor from the pool.
  450. Args:
  451. full_name (str): The full name of the extension descriptor to load.
  452. Returns:
  453. FieldDescriptor: The field descriptor for the named extension.
  454. Raises:
  455. KeyError: if the extension cannot be found in the pool.
  456. """
  457. full_name = _NormalizeFullyQualifiedName(full_name)
  458. try:
  459. # The proto compiler does not give any link between the FileDescriptor
  460. # and top-level extensions unless the FileDescriptorProto is added to
  461. # the DescriptorDatabase, but this can impact memory usage.
  462. # So we registered these extensions by name explicitly.
  463. return self._toplevel_extensions[full_name]
  464. except KeyError:
  465. pass
  466. message_name, _, extension_name = full_name.rpartition('.')
  467. try:
  468. # Most extensions are nested inside a message.
  469. scope = self.FindMessageTypeByName(message_name)
  470. except KeyError:
  471. # Some extensions are defined at file scope.
  472. scope = self._FindFileContainingSymbolInDb(full_name)
  473. return scope.extensions_by_name[extension_name]
  474. def FindExtensionByNumber(self, message_descriptor, number):
  475. """Gets the extension of the specified message with the specified number.
  476. Extensions have to be registered to this pool by calling :func:`Add` or
  477. :func:`AddExtensionDescriptor`.
  478. Args:
  479. message_descriptor (Descriptor): descriptor of the extended message.
  480. number (int): Number of the extension field.
  481. Returns:
  482. FieldDescriptor: The descriptor for the extension.
  483. Raises:
  484. KeyError: when no extension with the given number is known for the
  485. specified message.
  486. """
  487. try:
  488. return self._extensions_by_number[message_descriptor][number]
  489. except KeyError:
  490. self._TryLoadExtensionFromDB(message_descriptor, number)
  491. return self._extensions_by_number[message_descriptor][number]
  492. def FindAllExtensions(self, message_descriptor):
  493. """Gets all the known extensions of a given message.
  494. Extensions have to be registered to this pool by build related
  495. :func:`Add` or :func:`AddExtensionDescriptor`.
  496. Args:
  497. message_descriptor (Descriptor): Descriptor of the extended message.
  498. Returns:
  499. list[FieldDescriptor]: Field descriptors describing the extensions.
  500. """
  501. # Fallback to descriptor db if FindAllExtensionNumbers is provided.
  502. if self._descriptor_db and hasattr(
  503. self._descriptor_db, 'FindAllExtensionNumbers'):
  504. full_name = message_descriptor.full_name
  505. all_numbers = self._descriptor_db.FindAllExtensionNumbers(full_name)
  506. for number in all_numbers:
  507. if number in self._extensions_by_number[message_descriptor]:
  508. continue
  509. self._TryLoadExtensionFromDB(message_descriptor, number)
  510. return list(self._extensions_by_number[message_descriptor].values())
  511. def _TryLoadExtensionFromDB(self, message_descriptor, number):
  512. """Try to Load extensions from descriptor db.
  513. Args:
  514. message_descriptor: descriptor of the extended message.
  515. number: the extension number that needs to be loaded.
  516. """
  517. if not self._descriptor_db:
  518. return
  519. # Only supported when FindFileContainingExtension is provided.
  520. if not hasattr(
  521. self._descriptor_db, 'FindFileContainingExtension'):
  522. return
  523. full_name = message_descriptor.full_name
  524. file_proto = self._descriptor_db.FindFileContainingExtension(
  525. full_name, number)
  526. if file_proto is None:
  527. return
  528. try:
  529. self._ConvertFileProtoToFileDescriptor(file_proto)
  530. except:
  531. warn_msg = ('Unable to load proto file %s for extension number %d.' %
  532. (file_proto.name, number))
  533. warnings.warn(warn_msg, RuntimeWarning)
  534. def FindServiceByName(self, full_name):
  535. """Loads the named service descriptor from the pool.
  536. Args:
  537. full_name (str): The full name of the service descriptor to load.
  538. Returns:
  539. ServiceDescriptor: The service descriptor for the named service.
  540. Raises:
  541. KeyError: if the service cannot be found in the pool.
  542. """
  543. full_name = _NormalizeFullyQualifiedName(full_name)
  544. if full_name not in self._service_descriptors:
  545. self._FindFileContainingSymbolInDb(full_name)
  546. return self._service_descriptors[full_name]
  547. def FindMethodByName(self, full_name):
  548. """Loads the named service method descriptor from the pool.
  549. Args:
  550. full_name (str): The full name of the method descriptor to load.
  551. Returns:
  552. MethodDescriptor: The method descriptor for the service method.
  553. Raises:
  554. KeyError: if the method cannot be found in the pool.
  555. """
  556. full_name = _NormalizeFullyQualifiedName(full_name)
  557. service_name, _, method_name = full_name.rpartition('.')
  558. service_descriptor = self.FindServiceByName(service_name)
  559. return service_descriptor.methods_by_name[method_name]
  560. def _FindFileContainingSymbolInDb(self, symbol):
  561. """Finds the file in descriptor DB containing the specified symbol.
  562. Args:
  563. symbol (str): The name of the symbol to search for.
  564. Returns:
  565. FileDescriptor: The file that contains the specified symbol.
  566. Raises:
  567. KeyError: if the file cannot be found in the descriptor database.
  568. """
  569. try:
  570. file_proto = self._internal_db.FindFileContainingSymbol(symbol)
  571. except KeyError as error:
  572. if self._descriptor_db:
  573. file_proto = self._descriptor_db.FindFileContainingSymbol(symbol)
  574. else:
  575. raise error
  576. if not file_proto:
  577. raise KeyError('Cannot find a file containing %s' % symbol)
  578. return self._ConvertFileProtoToFileDescriptor(file_proto)
  579. def _ConvertFileProtoToFileDescriptor(self, file_proto):
  580. """Creates a FileDescriptor from a proto or returns a cached copy.
  581. This method also has the side effect of loading all the symbols found in
  582. the file into the appropriate dictionaries in the pool.
  583. Args:
  584. file_proto: The proto to convert.
  585. Returns:
  586. A FileDescriptor matching the passed in proto.
  587. """
  588. if file_proto.name not in self._file_descriptors:
  589. built_deps = list(self._GetDeps(file_proto.dependency))
  590. direct_deps = [self.FindFileByName(n) for n in file_proto.dependency]
  591. public_deps = [direct_deps[i] for i in file_proto.public_dependency]
  592. file_descriptor = descriptor.FileDescriptor(
  593. pool=self,
  594. name=file_proto.name,
  595. package=file_proto.package,
  596. syntax=file_proto.syntax,
  597. options=_OptionsOrNone(file_proto),
  598. serialized_pb=file_proto.SerializeToString(),
  599. dependencies=direct_deps,
  600. public_dependencies=public_deps,
  601. # pylint: disable=protected-access
  602. create_key=descriptor._internal_create_key)
  603. scope = {}
  604. # This loop extracts all the message and enum types from all the
  605. # dependencies of the file_proto. This is necessary to create the
  606. # scope of available message types when defining the passed in
  607. # file proto.
  608. for dependency in built_deps:
  609. scope.update(self._ExtractSymbols(
  610. dependency.message_types_by_name.values()))
  611. scope.update((_PrefixWithDot(enum.full_name), enum)
  612. for enum in dependency.enum_types_by_name.values())
  613. for message_type in file_proto.message_type:
  614. message_desc = self._ConvertMessageDescriptor(
  615. message_type, file_proto.package, file_descriptor, scope,
  616. file_proto.syntax)
  617. file_descriptor.message_types_by_name[message_desc.name] = (
  618. message_desc)
  619. for enum_type in file_proto.enum_type:
  620. file_descriptor.enum_types_by_name[enum_type.name] = (
  621. self._ConvertEnumDescriptor(enum_type, file_proto.package,
  622. file_descriptor, None, scope, True))
  623. for index, extension_proto in enumerate(file_proto.extension):
  624. extension_desc = self._MakeFieldDescriptor(
  625. extension_proto, file_proto.package, index, file_descriptor,
  626. is_extension=True)
  627. extension_desc.containing_type = self._GetTypeFromScope(
  628. file_descriptor.package, extension_proto.extendee, scope)
  629. self._SetFieldType(extension_proto, extension_desc,
  630. file_descriptor.package, scope)
  631. file_descriptor.extensions_by_name[extension_desc.name] = (
  632. extension_desc)
  633. self._file_desc_by_toplevel_extension[extension_desc.full_name] = (
  634. file_descriptor)
  635. for desc_proto in file_proto.message_type:
  636. self._SetAllFieldTypes(file_proto.package, desc_proto, scope)
  637. if file_proto.package:
  638. desc_proto_prefix = _PrefixWithDot(file_proto.package)
  639. else:
  640. desc_proto_prefix = ''
  641. for desc_proto in file_proto.message_type:
  642. desc = self._GetTypeFromScope(
  643. desc_proto_prefix, desc_proto.name, scope)
  644. file_descriptor.message_types_by_name[desc_proto.name] = desc
  645. for index, service_proto in enumerate(file_proto.service):
  646. file_descriptor.services_by_name[service_proto.name] = (
  647. self._MakeServiceDescriptor(service_proto, index, scope,
  648. file_proto.package, file_descriptor))
  649. self.Add(file_proto)
  650. self._file_descriptors[file_proto.name] = file_descriptor
  651. # Add extensions to the pool
  652. file_desc = self._file_descriptors[file_proto.name]
  653. for extension in file_desc.extensions_by_name.values():
  654. self._AddExtensionDescriptor(extension)
  655. for message_type in file_desc.message_types_by_name.values():
  656. for extension in message_type.extensions:
  657. self._AddExtensionDescriptor(extension)
  658. return file_desc
  659. def _ConvertMessageDescriptor(self, desc_proto, package=None, file_desc=None,
  660. scope=None, syntax=None):
  661. """Adds the proto to the pool in the specified package.
  662. Args:
  663. desc_proto: The descriptor_pb2.DescriptorProto protobuf message.
  664. package: The package the proto should be located in.
  665. file_desc: The file containing this message.
  666. scope: Dict mapping short and full symbols to message and enum types.
  667. syntax: string indicating syntax of the file ("proto2" or "proto3")
  668. Returns:
  669. The added descriptor.
  670. """
  671. if package:
  672. desc_name = '.'.join((package, desc_proto.name))
  673. else:
  674. desc_name = desc_proto.name
  675. if file_desc is None:
  676. file_name = None
  677. else:
  678. file_name = file_desc.name
  679. if scope is None:
  680. scope = {}
  681. nested = [
  682. self._ConvertMessageDescriptor(
  683. nested, desc_name, file_desc, scope, syntax)
  684. for nested in desc_proto.nested_type]
  685. enums = [
  686. self._ConvertEnumDescriptor(enum, desc_name, file_desc, None,
  687. scope, False)
  688. for enum in desc_proto.enum_type]
  689. fields = [self._MakeFieldDescriptor(field, desc_name, index, file_desc)
  690. for index, field in enumerate(desc_proto.field)]
  691. extensions = [
  692. self._MakeFieldDescriptor(extension, desc_name, index, file_desc,
  693. is_extension=True)
  694. for index, extension in enumerate(desc_proto.extension)]
  695. oneofs = [
  696. # pylint: disable=g-complex-comprehension
  697. descriptor.OneofDescriptor(desc.name, '.'.join((desc_name, desc.name)),
  698. index, None, [], desc.options,
  699. # pylint: disable=protected-access
  700. create_key=descriptor._internal_create_key)
  701. for index, desc in enumerate(desc_proto.oneof_decl)]
  702. extension_ranges = [(r.start, r.end) for r in desc_proto.extension_range]
  703. if extension_ranges:
  704. is_extendable = True
  705. else:
  706. is_extendable = False
  707. desc = descriptor.Descriptor(
  708. name=desc_proto.name,
  709. full_name=desc_name,
  710. filename=file_name,
  711. containing_type=None,
  712. fields=fields,
  713. oneofs=oneofs,
  714. nested_types=nested,
  715. enum_types=enums,
  716. extensions=extensions,
  717. options=_OptionsOrNone(desc_proto),
  718. is_extendable=is_extendable,
  719. extension_ranges=extension_ranges,
  720. file=file_desc,
  721. serialized_start=None,
  722. serialized_end=None,
  723. syntax=syntax,
  724. # pylint: disable=protected-access
  725. create_key=descriptor._internal_create_key)
  726. for nested in desc.nested_types:
  727. nested.containing_type = desc
  728. for enum in desc.enum_types:
  729. enum.containing_type = desc
  730. for field_index, field_desc in enumerate(desc_proto.field):
  731. if field_desc.HasField('oneof_index'):
  732. oneof_index = field_desc.oneof_index
  733. oneofs[oneof_index].fields.append(fields[field_index])
  734. fields[field_index].containing_oneof = oneofs[oneof_index]
  735. scope[_PrefixWithDot(desc_name)] = desc
  736. self._CheckConflictRegister(desc, desc.full_name, desc.file.name)
  737. self._descriptors[desc_name] = desc
  738. return desc
  739. def _ConvertEnumDescriptor(self, enum_proto, package=None, file_desc=None,
  740. containing_type=None, scope=None, top_level=False):
  741. """Make a protobuf EnumDescriptor given an EnumDescriptorProto protobuf.
  742. Args:
  743. enum_proto: The descriptor_pb2.EnumDescriptorProto protobuf message.
  744. package: Optional package name for the new message EnumDescriptor.
  745. file_desc: The file containing the enum descriptor.
  746. containing_type: The type containing this enum.
  747. scope: Scope containing available types.
  748. top_level: If True, the enum is a top level symbol. If False, the enum
  749. is defined inside a message.
  750. Returns:
  751. The added descriptor
  752. """
  753. if package:
  754. enum_name = '.'.join((package, enum_proto.name))
  755. else:
  756. enum_name = enum_proto.name
  757. if file_desc is None:
  758. file_name = None
  759. else:
  760. file_name = file_desc.name
  761. values = [self._MakeEnumValueDescriptor(value, index)
  762. for index, value in enumerate(enum_proto.value)]
  763. desc = descriptor.EnumDescriptor(name=enum_proto.name,
  764. full_name=enum_name,
  765. filename=file_name,
  766. file=file_desc,
  767. values=values,
  768. containing_type=containing_type,
  769. options=_OptionsOrNone(enum_proto),
  770. # pylint: disable=protected-access
  771. create_key=descriptor._internal_create_key)
  772. scope['.%s' % enum_name] = desc
  773. self._CheckConflictRegister(desc, desc.full_name, desc.file.name)
  774. self._enum_descriptors[enum_name] = desc
  775. # Add top level enum values.
  776. if top_level:
  777. for value in values:
  778. full_name = _NormalizeFullyQualifiedName(
  779. '.'.join((package, value.name)))
  780. self._CheckConflictRegister(value, full_name, file_name)
  781. self._top_enum_values[full_name] = value
  782. return desc
  783. def _MakeFieldDescriptor(self, field_proto, message_name, index,
  784. file_desc, is_extension=False):
  785. """Creates a field descriptor from a FieldDescriptorProto.
  786. For message and enum type fields, this method will do a look up
  787. in the pool for the appropriate descriptor for that type. If it
  788. is unavailable, it will fall back to the _source function to
  789. create it. If this type is still unavailable, construction will
  790. fail.
  791. Args:
  792. field_proto: The proto describing the field.
  793. message_name: The name of the containing message.
  794. index: Index of the field
  795. file_desc: The file containing the field descriptor.
  796. is_extension: Indication that this field is for an extension.
  797. Returns:
  798. An initialized FieldDescriptor object
  799. """
  800. if message_name:
  801. full_name = '.'.join((message_name, field_proto.name))
  802. else:
  803. full_name = field_proto.name
  804. return descriptor.FieldDescriptor(
  805. name=field_proto.name,
  806. full_name=full_name,
  807. index=index,
  808. number=field_proto.number,
  809. type=field_proto.type,
  810. cpp_type=None,
  811. message_type=None,
  812. enum_type=None,
  813. containing_type=None,
  814. label=field_proto.label,
  815. has_default_value=False,
  816. default_value=None,
  817. is_extension=is_extension,
  818. extension_scope=None,
  819. options=_OptionsOrNone(field_proto),
  820. file=file_desc,
  821. # pylint: disable=protected-access
  822. create_key=descriptor._internal_create_key)
  823. def _SetAllFieldTypes(self, package, desc_proto, scope):
  824. """Sets all the descriptor's fields's types.
  825. This method also sets the containing types on any extensions.
  826. Args:
  827. package: The current package of desc_proto.
  828. desc_proto: The message descriptor to update.
  829. scope: Enclosing scope of available types.
  830. """
  831. package = _PrefixWithDot(package)
  832. main_desc = self._GetTypeFromScope(package, desc_proto.name, scope)
  833. if package == '.':
  834. nested_package = _PrefixWithDot(desc_proto.name)
  835. else:
  836. nested_package = '.'.join([package, desc_proto.name])
  837. for field_proto, field_desc in zip(desc_proto.field, main_desc.fields):
  838. self._SetFieldType(field_proto, field_desc, nested_package, scope)
  839. for extension_proto, extension_desc in (
  840. zip(desc_proto.extension, main_desc.extensions)):
  841. extension_desc.containing_type = self._GetTypeFromScope(
  842. nested_package, extension_proto.extendee, scope)
  843. self._SetFieldType(extension_proto, extension_desc, nested_package, scope)
  844. for nested_type in desc_proto.nested_type:
  845. self._SetAllFieldTypes(nested_package, nested_type, scope)
  846. def _SetFieldType(self, field_proto, field_desc, package, scope):
  847. """Sets the field's type, cpp_type, message_type and enum_type.
  848. Args:
  849. field_proto: Data about the field in proto format.
  850. field_desc: The descriptor to modify.
  851. package: The package the field's container is in.
  852. scope: Enclosing scope of available types.
  853. """
  854. if field_proto.type_name:
  855. desc = self._GetTypeFromScope(package, field_proto.type_name, scope)
  856. else:
  857. desc = None
  858. if not field_proto.HasField('type'):
  859. if isinstance(desc, descriptor.Descriptor):
  860. field_proto.type = descriptor.FieldDescriptor.TYPE_MESSAGE
  861. else:
  862. field_proto.type = descriptor.FieldDescriptor.TYPE_ENUM
  863. field_desc.cpp_type = descriptor.FieldDescriptor.ProtoTypeToCppProtoType(
  864. field_proto.type)
  865. if (field_proto.type == descriptor.FieldDescriptor.TYPE_MESSAGE
  866. or field_proto.type == descriptor.FieldDescriptor.TYPE_GROUP):
  867. field_desc.message_type = desc
  868. if field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM:
  869. field_desc.enum_type = desc
  870. if field_proto.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  871. field_desc.has_default_value = False
  872. field_desc.default_value = []
  873. elif field_proto.HasField('default_value'):
  874. field_desc.has_default_value = True
  875. if (field_proto.type == descriptor.FieldDescriptor.TYPE_DOUBLE or
  876. field_proto.type == descriptor.FieldDescriptor.TYPE_FLOAT):
  877. field_desc.default_value = float(field_proto.default_value)
  878. elif field_proto.type == descriptor.FieldDescriptor.TYPE_STRING:
  879. field_desc.default_value = field_proto.default_value
  880. elif field_proto.type == descriptor.FieldDescriptor.TYPE_BOOL:
  881. field_desc.default_value = field_proto.default_value.lower() == 'true'
  882. elif field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM:
  883. field_desc.default_value = field_desc.enum_type.values_by_name[
  884. field_proto.default_value].number
  885. elif field_proto.type == descriptor.FieldDescriptor.TYPE_BYTES:
  886. field_desc.default_value = text_encoding.CUnescape(
  887. field_proto.default_value)
  888. elif field_proto.type == descriptor.FieldDescriptor.TYPE_MESSAGE:
  889. field_desc.default_value = None
  890. else:
  891. # All other types are of the "int" type.
  892. field_desc.default_value = int(field_proto.default_value)
  893. else:
  894. field_desc.has_default_value = False
  895. if (field_proto.type == descriptor.FieldDescriptor.TYPE_DOUBLE or
  896. field_proto.type == descriptor.FieldDescriptor.TYPE_FLOAT):
  897. field_desc.default_value = 0.0
  898. elif field_proto.type == descriptor.FieldDescriptor.TYPE_STRING:
  899. field_desc.default_value = u''
  900. elif field_proto.type == descriptor.FieldDescriptor.TYPE_BOOL:
  901. field_desc.default_value = False
  902. elif field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM:
  903. field_desc.default_value = field_desc.enum_type.values[0].number
  904. elif field_proto.type == descriptor.FieldDescriptor.TYPE_BYTES:
  905. field_desc.default_value = b''
  906. elif field_proto.type == descriptor.FieldDescriptor.TYPE_MESSAGE:
  907. field_desc.default_value = None
  908. else:
  909. # All other types are of the "int" type.
  910. field_desc.default_value = 0
  911. field_desc.type = field_proto.type
  912. def _MakeEnumValueDescriptor(self, value_proto, index):
  913. """Creates a enum value descriptor object from a enum value proto.
  914. Args:
  915. value_proto: The proto describing the enum value.
  916. index: The index of the enum value.
  917. Returns:
  918. An initialized EnumValueDescriptor object.
  919. """
  920. return descriptor.EnumValueDescriptor(
  921. name=value_proto.name,
  922. index=index,
  923. number=value_proto.number,
  924. options=_OptionsOrNone(value_proto),
  925. type=None,
  926. # pylint: disable=protected-access
  927. create_key=descriptor._internal_create_key)
  928. def _MakeServiceDescriptor(self, service_proto, service_index, scope,
  929. package, file_desc):
  930. """Make a protobuf ServiceDescriptor given a ServiceDescriptorProto.
  931. Args:
  932. service_proto: The descriptor_pb2.ServiceDescriptorProto protobuf message.
  933. service_index: The index of the service in the File.
  934. scope: Dict mapping short and full symbols to message and enum types.
  935. package: Optional package name for the new message EnumDescriptor.
  936. file_desc: The file containing the service descriptor.
  937. Returns:
  938. The added descriptor.
  939. """
  940. if package:
  941. service_name = '.'.join((package, service_proto.name))
  942. else:
  943. service_name = service_proto.name
  944. methods = [self._MakeMethodDescriptor(method_proto, service_name, package,
  945. scope, index)
  946. for index, method_proto in enumerate(service_proto.method)]
  947. desc = descriptor.ServiceDescriptor(
  948. name=service_proto.name,
  949. full_name=service_name,
  950. index=service_index,
  951. methods=methods,
  952. options=_OptionsOrNone(service_proto),
  953. file=file_desc,
  954. # pylint: disable=protected-access
  955. create_key=descriptor._internal_create_key)
  956. self._CheckConflictRegister(desc, desc.full_name, desc.file.name)
  957. self._service_descriptors[service_name] = desc
  958. return desc
  959. def _MakeMethodDescriptor(self, method_proto, service_name, package, scope,
  960. index):
  961. """Creates a method descriptor from a MethodDescriptorProto.
  962. Args:
  963. method_proto: The proto describing the method.
  964. service_name: The name of the containing service.
  965. package: Optional package name to look up for types.
  966. scope: Scope containing available types.
  967. index: Index of the method in the service.
  968. Returns:
  969. An initialized MethodDescriptor object.
  970. """
  971. full_name = '.'.join((service_name, method_proto.name))
  972. input_type = self._GetTypeFromScope(
  973. package, method_proto.input_type, scope)
  974. output_type = self._GetTypeFromScope(
  975. package, method_proto.output_type, scope)
  976. return descriptor.MethodDescriptor(
  977. name=method_proto.name,
  978. full_name=full_name,
  979. index=index,
  980. containing_service=None,
  981. input_type=input_type,
  982. output_type=output_type,
  983. options=_OptionsOrNone(method_proto),
  984. # pylint: disable=protected-access
  985. create_key=descriptor._internal_create_key)
  986. def _ExtractSymbols(self, descriptors):
  987. """Pulls out all the symbols from descriptor protos.
  988. Args:
  989. descriptors: The messages to extract descriptors from.
  990. Yields:
  991. A two element tuple of the type name and descriptor object.
  992. """
  993. for desc in descriptors:
  994. yield (_PrefixWithDot(desc.full_name), desc)
  995. for symbol in self._ExtractSymbols(desc.nested_types):
  996. yield symbol
  997. for enum in desc.enum_types:
  998. yield (_PrefixWithDot(enum.full_name), enum)
  999. def _GetDeps(self, dependencies):
  1000. """Recursively finds dependencies for file protos.
  1001. Args:
  1002. dependencies: The names of the files being depended on.
  1003. Yields:
  1004. Each direct and indirect dependency.
  1005. """
  1006. for dependency in dependencies:
  1007. dep_desc = self.FindFileByName(dependency)
  1008. yield dep_desc
  1009. for parent_dep in dep_desc.dependencies:
  1010. yield parent_dep
  1011. def _GetTypeFromScope(self, package, type_name, scope):
  1012. """Finds a given type name in the current scope.
  1013. Args:
  1014. package: The package the proto should be located in.
  1015. type_name: The name of the type to be found in the scope.
  1016. scope: Dict mapping short and full symbols to message and enum types.
  1017. Returns:
  1018. The descriptor for the requested type.
  1019. """
  1020. if type_name not in scope:
  1021. components = _PrefixWithDot(package).split('.')
  1022. while components:
  1023. possible_match = '.'.join(components + [type_name])
  1024. if possible_match in scope:
  1025. type_name = possible_match
  1026. break
  1027. else:
  1028. components.pop(-1)
  1029. return scope[type_name]
  1030. def _PrefixWithDot(name):
  1031. return name if name.startswith('.') else '.%s' % name
  1032. if _USE_C_DESCRIPTORS:
  1033. # TODO(amauryfa): This pool could be constructed from Python code, when we
  1034. # support a flag like 'use_cpp_generated_pool=True'.
  1035. # pylint: disable=protected-access
  1036. _DEFAULT = descriptor._message.default_pool
  1037. else:
  1038. _DEFAULT = DescriptorPool()
  1039. def Default():
  1040. return _DEFAULT