Looping over Protocol Buffers attributes in Python

前端 未结 1 1498
走了就别回头了
走了就别回头了 2021-02-07 04:29

I would like help with recursively looping over all attributes/sub objects contained in a protocol buffers message, assuming that we do not know the names of them, or how many t

相关标签:
1条回答
  • 2021-02-07 05:10

    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 addressbook
    
    person = 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 Doe
    tutorial.Person.id: 1234
    tutorial.Person.email: foo@example.com
    tutorial.Person.PhoneNumber.number: 1234567890
    tutorial.Person.PhoneNumber.type: HOME
    
    0 讨论(0)
提交回复
热议问题