Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Dynamically reading a Protobuf FileDescriptorSet file into Python message classes
#!/usr/bin/env python
Read a serialized Protobuf FileDescriptorSet that was
generated from the protoc tool, and dynamically generate
the python classes for each message.
import sys
from google.protobuf import descriptor_pb2
from google.protobuf import reflection
from google.protobuf import symbol_database
def gen(desc_file, db=None):
if not db:
db = symbol_database.Default()
with open(desc_file, 'rb') as fh:
fds = descriptor_pb2.FileDescriptorSet.FromString(
generated = {}
for prot in fds.file:
fd = db.pool.Add(prot)
for name in fd.message_types_by_name:
mdesc = fd.message_types_by_name[name]
Klass = reflection.MakeClass(mdesc)
generated[(fd.package, name)] = db.RegisterMessage(Klass)
return generated
if __name__ == '__main__':
from pprint import pprint
generated = gen(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment