reflection.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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. # This code is meant to work on Python 2.4 and above only.
  31. """Contains a metaclass and helper functions used to create
  32. protocol message classes from Descriptor objects at runtime.
  33. Recall that a metaclass is the "type" of a class.
  34. (A class is to a metaclass what an instance is to a class.)
  35. In this case, we use the GeneratedProtocolMessageType metaclass
  36. to inject all the useful functionality into the classes
  37. output by the protocol compiler at compile-time.
  38. The upshot of all this is that the real implementation
  39. details for ALL pure-Python protocol buffers are *here in
  40. this file*.
  41. """
  42. __author__ = 'robinson@google.com (Will Robinson)'
  43. from google.protobuf.internal import api_implementation
  44. from google.protobuf import descriptor as descriptor_mod
  45. from google.protobuf import message
  46. _FieldDescriptor = descriptor_mod.FieldDescriptor
  47. if api_implementation.Type() == 'cpp':
  48. from google.protobuf.pyext import cpp_message as message_impl
  49. else:
  50. from google.protobuf.internal import python_message as message_impl
  51. _NewMessage = message_impl.NewMessage
  52. _InitMessage = message_impl.InitMessage
  53. class GeneratedProtocolMessageType(type):
  54. """Metaclass for protocol message classes created at runtime from Descriptors.
  55. We add implementations for all methods described in the Message class. We
  56. also create properties to allow getting/setting all fields in the protocol
  57. message. Finally, we create slots to prevent users from accidentally
  58. "setting" nonexistent fields in the protocol message, which then wouldn't get
  59. serialized / deserialized properly.
  60. The protocol compiler currently uses this metaclass to create protocol
  61. message classes at runtime. Clients can also manually create their own
  62. classes at runtime, as in this example:
  63. mydescriptor = Descriptor(.....)
  64. class MyProtoClass(Message):
  65. __metaclass__ = GeneratedProtocolMessageType
  66. DESCRIPTOR = mydescriptor
  67. myproto_instance = MyProtoClass()
  68. myproto.foo_field = 23
  69. ...
  70. The above example will not work for nested types. If you wish to include them,
  71. use reflection.MakeClass() instead of manually instantiating the class in
  72. order to create the appropriate class structure.
  73. """
  74. # Must be consistent with the protocol-compiler code in
  75. # proto2/compiler/internal/generator.*.
  76. _DESCRIPTOR_KEY = 'DESCRIPTOR'
  77. def __new__(cls, name, bases, dictionary):
  78. """Custom allocation for runtime-generated class types.
  79. We override __new__ because this is apparently the only place
  80. where we can meaningfully set __slots__ on the class we're creating(?).
  81. (The interplay between metaclasses and slots is not very well-documented).
  82. Args:
  83. name: Name of the class (ignored, but required by the
  84. metaclass protocol).
  85. bases: Base classes of the class we're constructing.
  86. (Should be message.Message). We ignore this field, but
  87. it's required by the metaclass protocol
  88. dictionary: The class dictionary of the class we're
  89. constructing. dictionary[_DESCRIPTOR_KEY] must contain
  90. a Descriptor object describing this protocol message
  91. type.
  92. Returns:
  93. Newly-allocated class.
  94. """
  95. descriptor = dictionary[GeneratedProtocolMessageType._DESCRIPTOR_KEY]
  96. bases = _NewMessage(bases, descriptor, dictionary)
  97. superclass = super(GeneratedProtocolMessageType, cls)
  98. new_class = superclass.__new__(cls, name, bases, dictionary)
  99. return new_class
  100. def __init__(cls, name, bases, dictionary):
  101. """Here we perform the majority of our work on the class.
  102. We add enum getters, an __init__ method, implementations
  103. of all Message methods, and properties for all fields
  104. in the protocol type.
  105. Args:
  106. name: Name of the class (ignored, but required by the
  107. metaclass protocol).
  108. bases: Base classes of the class we're constructing.
  109. (Should be message.Message). We ignore this field, but
  110. it's required by the metaclass protocol
  111. dictionary: The class dictionary of the class we're
  112. constructing. dictionary[_DESCRIPTOR_KEY] must contain
  113. a Descriptor object describing this protocol message
  114. type.
  115. """
  116. descriptor = dictionary[GeneratedProtocolMessageType._DESCRIPTOR_KEY]
  117. _InitMessage(descriptor, cls)
  118. superclass = super(GeneratedProtocolMessageType, cls)
  119. superclass.__init__(name, bases, dictionary)
  120. setattr(descriptor, '_concrete_class', cls)
  121. def ParseMessage(descriptor, byte_str):
  122. """Generate a new Message instance from this Descriptor and a byte string.
  123. Args:
  124. descriptor: Protobuf Descriptor object
  125. byte_str: Serialized protocol buffer byte string
  126. Returns:
  127. Newly created protobuf Message object.
  128. """
  129. result_class = MakeClass(descriptor)
  130. new_msg = result_class()
  131. new_msg.ParseFromString(byte_str)
  132. return new_msg
  133. def MakeClass(descriptor):
  134. """Construct a class object for a protobuf described by descriptor.
  135. Composite descriptors are handled by defining the new class as a member of the
  136. parent class, recursing as deep as necessary.
  137. This is the dynamic equivalent to:
  138. class Parent(message.Message):
  139. __metaclass__ = GeneratedProtocolMessageType
  140. DESCRIPTOR = descriptor
  141. class Child(message.Message):
  142. __metaclass__ = GeneratedProtocolMessageType
  143. DESCRIPTOR = descriptor.nested_types[0]
  144. Sample usage:
  145. file_descriptor = descriptor_pb2.FileDescriptorProto()
  146. file_descriptor.ParseFromString(proto2_string)
  147. msg_descriptor = descriptor.MakeDescriptor(file_descriptor.message_type[0])
  148. msg_class = reflection.MakeClass(msg_descriptor)
  149. msg = msg_class()
  150. Args:
  151. descriptor: A descriptor.Descriptor object describing the protobuf.
  152. Returns:
  153. The Message class object described by the descriptor.
  154. """
  155. attributes = {}
  156. for name, nested_type in descriptor.nested_types_by_name.items():
  157. attributes[name] = MakeClass(nested_type)
  158. attributes[GeneratedProtocolMessageType._DESCRIPTOR_KEY] = descriptor
  159. return GeneratedProtocolMessageType(str(descriptor.name), (message.Message,),
  160. attributes)