dynamic deserialize message in Python

105 views
Skip to first unread message

Ruslan Mullakhmetov

unread,
Jun 27, 2011, 8:33:54 AM6/27/11
to prot...@googlegroups.com
Hi

   I'm trying to deserialize different protobuf messages in python. Is the any way to get message type from unserialized message?

   Like dynamic message in cpp and java ?

   Thanks.

Eric Hopper

unread,
Jun 30, 2011, 10:47:38 AM6/30/11
to Protocol Buffers
Presumably you're using the pattern where you have a containing
message and all of your sub-messages are optional fields of the
containing message, but you only ever expect one of those sub-fields
to be set.

message Hello {
optional string name = 1;
optional reply_cookie = 2;
}

message ILoveYou {
optional float strength = 1;
}

message WontYouTellMeYourName {
required uint64 reply_cookie = 1;
}

message Doors {
optional Hello hello = 1;
optional ILoveYou i_love_you = 2;
optional WontYouTellMeYourName name_request = 3;
}

In Python, you can do something like:

doors = Doors.FromString(s)
doors.ListFields()[0][0].number

And you will get a number like 1, 2 or 3 depending on which message
you're being sent. You might also get an IndexError exception if
someone sent you a message sub-messages in it at all.

The ListFields function gives you a list of (descriptor,
message_object) tuples. The descriptor describes the message_object in
the terms of the enclosing message, and one of the things a descriptor
records is the field id for the message object.

Ruslan Mullakhmetov

unread,
Jul 1, 2011, 9:12:26 AM7/1/11
to prot...@googlegroups.com
thanks you. I will try to use it. 
Reply all
Reply to author
Forward
0 new messages