Skip to content
/ pb2dict Public

Protobuf messages to Python dictionary with optional custom conversions.

License

Notifications You must be signed in to change notification settings

qvecs/pb2dict

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Protobuf to Dictionary (pb2dict)

Utility to convert Protobuf messages to dictionary with optional custom conversions.

Install

pip install pb2dict

Usage

Basic Usage

from message_pb2 import Message
from pb2dict import to_dict, to_message

msg = Message(msg=b"hello")

msg_dict = to_dict(msg)
# {'msg': b'hello'}

msg_original = to_message(Message, msg_dict)
# Message(msg=b'hello')

Custom Conversions

Use fields to specify overrides for particular field types.

import base64
from message_pb2 import Message

from pb2dict import to_dict, to_message, fields

msg = Message(msg=b"hello")

msg_dict = to_dict(
    pb=msg,
    fields={fields.BYTES: lambda raw: base64.b64encode(raw).decode("utf-8")},
)
# {'msg': 'aGVsbG8='}

original_msg = to_message(
    pb=Message,
    data=msg_dict,
    fields={fields.BYTES: lambda txt: base64.b64decode(txt)},
)
# Message(msg=b'hello')

fields Type

class fields:
    DOUBLE
    FLOAT
    INT32
    INT64
    UINT32
    UINT64
    SINT32
    SINT64
    FIXED32
    FIXED64
    SFIXED32
    SFIXED64
    BOOL
    STRING
    BYTES
    ENUM

About

Protobuf messages to Python dictionary with optional custom conversions.

Topics

Resources

License

Stars

Watchers

Forks

Languages