Looping over Protocol Buffers attributes in Python Looping over Protocol Buffers attributes in Python python python

Looping over Protocol Buffers attributes in Python


I'm not super familiar with protobufs, so there may well be an easier way or api for this kind of thing. However, below shows an example of how you could iterate/introspect and objects fields and print them out. Hopefully enough to get you going in the right direction at least...

import addressbook_pb2 as addressbookperson = addressbook.Person(id=1234, name="John Doe", email="foo@example.com")person.phone.add(number="1234567890")def dump_object(obj):    for descriptor in obj.DESCRIPTOR.fields:        value = getattr(obj, descriptor.name)        if descriptor.type == descriptor.TYPE_MESSAGE:            if descriptor.label == descriptor.LABEL_REPEATED:                map(dump_object, value)            else:                dump_object(value)        elif descriptor.type == descriptor.TYPE_ENUM:            enum_name = descriptor.enum_type.values[value].name            print "%s: %s" % (descriptor.full_name, enum_name)        else:            print "%s: %s" % (descriptor.full_name, value)dump_object(person)

which outputs

tutorial.Person.name: John Doetutorial.Person.id: 1234tutorial.Person.email: foo@example.comtutorial.Person.PhoneNumber.number: 1234567890tutorial.Person.PhoneNumber.type: HOME