Hatch Protobuf Plugin

0.5.0 · active · verified Thu Apr 16

Hatch-protobuf is a Hatch build plugin designed to automatically generate Python files from Protocol Buffers (.proto) definitions. It leverages `grpcio-tools` internally to invoke the `protoc` compiler, streamlining the integration of Protobuf schema compilation into the standard Python build process. As of version 0.5.0, it is actively maintained, though its release cadence is tied to the broader Hatch and Hatchling ecosystem.

Common errors

Warnings

Install

Imports

Quickstart

To quickly use `hatch-protobuf`, first configure your `pyproject.toml` file to include the plugin and define the paths for your `.proto` files and where the generated Python modules should be placed. Ensure `grpcio-tools` and `protobuf` are listed as dependencies for the build hook. Then, place your `.proto` definitions in the specified `proto-paths`. After running `hatch build` or setting up your development environment (e.g., `hatch env run pip install -e .`), the generated Python modules can be imported and used like any other Protobuf-generated code.

# pyproject.toml
[build-system]
requires = ["hatchling>=1.12.0", "hatch-protobuf~=0.5.0"]
build-backend = "hatchling.build"

[tool.hatch.build.hooks.protobuf]
proto-paths = ["src/my_package/protos"] # Directory containing your .proto files
output-path = "src/my_package/protos" # Where to place generated Python files
dependencies = [
    "grpcio-tools~=1.48", # Specific versions often needed for compatibility
    "protobuf>=3.19"
]

# src/my_package/protos/example.proto
syntax = "proto3";

package my_package.protos;

message MyMessage {
  string name = 1;
  int32 id = 2;
}

# src/my_package/main.py (after running hatch build or in dev environment)
from my_package.protos import example_pb2

message = example_pb2.MyMessage(name="Alice", id=123)
print(f"Created Protobuf message: {message.name}, {message.id}")

view raw JSON →