Protobuf 3 to Python Dict Converter

0.1.5 · active · verified Thu Apr 09

A Python library designed to convert Protocol Buffer 3 messages into standard Python dictionaries and vice-versa. It is particularly useful as an intermediate step for serialization tasks, such as converting Protobuf messages to JSON. The library is a Python 3 adaptation of an earlier project and currently maintains version 0.1.5, with infrequent updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates converting a `google.protobuf.Timestamp` message to a Python dictionary and back. For custom Protobuf messages, you would first need to compile your `.proto` files into Python classes using the `protoc` compiler.

from google.protobuf.timestamp_pb2 import Timestamp
from protobuf_to_dict import protobuf_to_dict, dict_to_protobuf
import datetime

# Create a Protobuf Timestamp message
dt_obj = datetime.datetime.now(datetime.timezone.utc)
timestamp_msg = Timestamp()
timestamp_msg.FromDatetime(dt_obj)

print(f"Original Protobuf Timestamp: {timestamp_msg}")

# Convert Protobuf message to Python dictionary
data_dict = protobuf_to_dict(timestamp_msg)
print(f"Converted dictionary: {data_dict}")

# Convert dictionary back to Protobuf message
new_timestamp_msg = dict_to_protobuf(Timestamp, data_dict)
print(f"Converted back to Protobuf: {new_timestamp_msg}")

# Verify conversion
assert new_timestamp_msg.seconds == timestamp_msg.seconds
assert new_timestamp_msg.nanos == timestamp_msg.nanos
print("Conversion verified successfully!")

view raw JSON →