title: Looping over Protocol Buffers attributes in Python
body: <p>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 there are.</p>
  
  <p>As an example, take the following .proto file from the tutorial on the google website:</p>
  
  <pre><code>  message Person {
      required string name = 1;
      required int32 id = 2;
      optional string email = 3;
  
    enum PhoneType {
      MOBILE = 0;
      HOME = 1;
      WORK = 2;
    }
  
    message PhoneNumber {
      required string number = 1;
      optional PhoneType type = 2 [default = HOME];
    }
  
    repeated PhoneNumber phone = 4;
  }
  </code></pre>
  
  <p>and to use it...:</p>
  
  <pre><code>person = tutorial.Person()
  person.id = 1234
  person.name = "John Doe"
  person.email = "jdoe@example.com"
  phone = person.phone.add()
  phone.number = "555-4321"
  phone.type = tutorial.Person.HOME
  </code></pre>
  
  <p>Given <code>Person</code>, How do I then access both the name of the attribute and its value for each element: <code>person.id</code>, <code>person.name</code>, <code>person.email</code>, <code>person.phone.number</code>, <code>person.phone.type</code>?</p>
  
  <p>I have tried the following, however it doesn't seem to recurs into <code>person.phone.number</code> or <code>person.phone.type</code>.</p>
  
  <pre><code>object_of_interest = Person
  
  while( hasattr(object_of_interest, "_fields") ):
    for obj in object_of_interest._fields:
      # Do_something_with_object(obj) # eg print obj.name
      object_of_interest = obj
  </code></pre>
  
  <p>I have tried using <code>obj.DESCRIPTOR.fields_by_name.keys</code> to access the sub elements, but these are the string representations of the sub objects, not the objects themselves.</p>
  
  <p>obj.name gives me the attribute of the name, but im not sure how to actually get the value of that attribute, eg obj.name may give me 'name', but how do i get 'john doe' out of it?</p>