Skip to content

Instantly share code, notes, and snippets.

@jclosure
Created February 7, 2021 02:54
Show Gist options
  • Save jclosure/16b394b990033ce46bafa7b1708b8c5b to your computer and use it in GitHub Desktop.
Save jclosure/16b394b990033ce46bafa7b1708b8c5b to your computer and use it in GitHub Desktop.
Generic Python Protobuf <-> Dictionary: encoder/decoder functions
from google.protobuf.json_format import MessageToDict
from google.protobuf.json_format import ParseDict
def encode(dictObj, pb_class):
"""Takes in a dict and returns the serialized binary of pb_class"""
# pb = dict_to_protobuf(pb_class, dict)
pb = pb_class()
pb = ParseDict(dictObj, pb, ignore_unknown_fields=True)
return pb.SerializeToString()
def decode(bin, pb_class):
"""Takes the serialized {value for value in variable}binary of an instance of the pb_class and returns a dict"""
pb = pb_class()
pb.ParseFromString(bin)
return MessageToDict(pb, including_default_value_fields=True, preserving_proto_field_name=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment