31 """Provides a factory class for generating dynamic messages.
33 The easiest way to use this class is if you have access to the FileDescriptor
34 protos containing the messages you want to create you can just do the following:
36 message_classes = message_factory.GetMessages(iterable_of_file_descriptors)
37 my_proto_instance = message_classes['some.proto.package.MessageName']()
40 __author__ =
'matthewtoia@google.com (Matt Toia)'
46 if api_implementation.Type() ==
'cpp':
53 _GENERATED_PROTOCOL_MESSAGE_TYPE = message_impl.GeneratedProtocolMessageType
57 """Factory for creating Proto2 messages from descriptors in a pool."""
60 """Initializes a new factory."""
67 """Builds a proto2 message class based on the passed in descriptor.
69 Passing a descriptor with a fully qualified name matching a previous
70 invocation will cause the same class to be returned.
73 descriptor: The descriptor to build from.
76 A class describing the passed in descriptor.
79 descriptor_name = descriptor.name
81 descriptor_name = descriptor.name.encode(
'ascii',
'ignore')
85 {
'DESCRIPTOR': descriptor,
'__module__':
None})
87 self.
_classes[descriptor] = result_class
88 for field
in descriptor.fields:
89 if field.message_type:
91 for extension
in result_class.DESCRIPTOR.extensions:
92 if extension.containing_type
not in self.
_classes:
94 extended_class = self.
_classes[extension.containing_type]
95 extended_class.RegisterExtension(extension)
99 """Gets all the messages from a specified file.
101 This will find and resolve dependencies, failing if the descriptor
102 pool cannot satisfy them.
105 files: The file names to extract messages from.
108 A dictionary mapping proto names to the message classes. This will include
109 any dependent messages as well as any messages defined in the same file as
113 for file_name
in files:
115 for desc
in file_desc.message_types_by_name.values():
127 for extension
in file_desc.extensions_by_name.values():
128 if extension.containing_type
not in self.
_classes:
130 extended_class = self.
_classes[extension.containing_type]
131 extended_class.RegisterExtension(extension)
139 """Builds a dictionary of all the messages available in a set of files.
142 file_protos: Iterable of FileDescriptorProto to build messages out of.
145 A dictionary mapping proto names to the message classes. This will include
146 any dependent messages as well as any messages defined in the same file as
151 file_by_name = {file_proto.name: file_proto
for file_proto
in file_protos}
152 def _AddFile(file_proto):
153 for dependency
in file_proto.dependency:
154 if dependency
in file_by_name:
156 _AddFile(file_by_name.pop(dependency))
157 _FACTORY.pool.Add(file_proto)
159 _AddFile(file_by_name.popitem()[1])
160 return _FACTORY.GetMessages([file_proto.name
for file_proto
in file_protos])