Betterproto: A Protobuf & gRPC Library for Python

1.2.5 · active · verified Fri Apr 10

Betterproto is a Python library that generates Python dataclasses, Protobuf serialization, and gRPC client/server stubs directly from `.proto` files. It aims to provide a more Pythonic interface than the official `protobuf` library. The current stable version is 1.2.5, but a 2.0.0 beta is under active development, introducing significant breaking changes and new features. Releases are somewhat irregular, with recent focus on the 2.0.0 branch.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a `.proto` file, compile it using `protoc` with the `betterproto` plugin, and then interact with the generated Python message classes. It covers basic message instantiation, serialization, and deserialization. Ensure the Protocol Buffers compiler (`protoc`) is installed and available in your system's PATH.

import os
from pathlib import Path
import subprocess
import sys

# 1. Define a .proto file
proto_content = """
syntax = "proto3";

message GreetRequest {
  string name = 1;
}

message GreetResponse {
  string greeting = 1;
}
"""
proto_file_path = Path("greet.proto")
proto_file_path.write_text(proto_content)

# 2. Compile the .proto file using protoc with betterproto plugin
#    Ensure `protoc` is installed and in your PATH.
#    The betterproto Python package ships its own protoc plugin.

try:
    # Find the betterproto plugin
    betterproto_plugin = next(
        p for p in sys.path if 'betterproto' in p and 'site-packages' in p
    ) + '/betterproto/plugin/protoc-gen-python_betterproto'

    print(f"Using betterproto plugin: {betterproto_plugin}")

    compile_command = [
        "protoc",
        f"--plugin=protoc-gen-python_betterproto={betterproto_plugin}",
        "--python_betterproto_out=.",
        str(proto_file_path)
    ]
    subprocess.run(compile_command, check=True, capture_output=True)
    print("Proto file compiled successfully to greet.py")

    # 3. Use the generated Python code
    from greet import GreetRequest, GreetResponse

    request = GreetRequest(name="World")
    print(f"Created request: {request.name}")

    # Serialize the message
    serialized_data = bytes(request)
    print(f"Serialized data (bytes): {serialized_data}")

    # Deserialize the message
    deserialized_request = GreetRequest().parse(serialized_data)
    print(f"Deserialized request: {deserialized_request.name}")

    response = GreetResponse(greeting=f"Hello, {deserialized_request.name}!")
    print(f"Created response: {response.greeting}")

except FileNotFoundError:
    print("Error: 'protoc' command not found. Please install Protocol Buffers compiler.")
except subprocess.CalledProcessError as e:
    print(f"Error compiling proto file: {e.stderr.decode()}")
except ImportError:
    print("Error: Could not import generated 'greet' module. Compilation might have failed or plugin path is incorrect.")
finally:
    # Clean up generated files
    Path("greet.py").unlink(missing_ok=True)
    Path("greet.proto").unlink(missing_ok=True)
    print("Cleaned up temporary files.")

view raw JSON →