Google Protocol Buffers Tools

0.47.0 · active · verified Fri Apr 17

`pbtools` is a Python library for working with Google Protocol Buffers. It provides tools to read, write, encode, and decode Protocol Buffers messages (both binary and text) directly from `.proto` definitions, *without* requiring generated Python code. This simplifies field access and enables decoding of unknown messages. The current version is 0.47.0, and it maintains an active release cadence with incremental updates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a Protocol Buffer message, build a database from its `.proto` definition, create a message instance, encode it to binary, and then decode it back using `pbtools`. It highlights the direct interaction with messages without code generation.

import pbtools
import os

# Example .proto file content
proto_file_content = """
syntax = "proto3";

message MyMessage {
    int32 id = 1;
    string name = 2;
    repeated int32 values = 3;
}
"""
# For simplicity, write to a temporary file
proto_path = "my_message.proto"
with open(proto_path, "w") as f:
    f.write(proto_file_content)

# Build a database from .proto files
database = pbtools.build_database([proto_path])

# Get the message type from the database
MyMessage = database.MyMessage

# Create a message instance
message = MyMessage(id=1, name="hello", values=[10, 20, 30])
print(f"Original message: {message}")

# Encode to binary
encoded = message.encode()
print(f"Encoded bytes: {encoded}")

# Decode from binary
decoded = MyMessage.decode(encoded)
print(f"Decoded message: {decoded}")

# Access fields
print(f"Decoded ID: {decoded.id}")
print(f"Decoded Name: {decoded.name}")
print(f"Decoded Values: {decoded.values}")

# Clean up the temporary file
os.remove(proto_path)

view raw JSON →