Mypy Protobuf Stubs Generator

5.0.0 · active · verified Wed Apr 08

mypy-protobuf is a Python library and `protoc` plugin that generates mypy stub files (.pyi files) from Protocol Buffer (.proto) specifications. It ensures type safety for Python code interacting with protobuf messages and gRPC services, providing more accurate and detailed type information than the standard `protoc --pyi_out` option. Currently at version 5.0.0, it maintains an active release cadence with frequent updates.

Warnings

Install

Quickstart

This quickstart demonstrates how to generate Python protobuf code and mypy stubs from a `.proto` file, and then use `mypy` to type-check Python code that consumes these generated types. It first creates a sample `.proto` file, then uses `protoc` with the `mypy-protobuf` plugin to generate the `.py` and `.pyi` files. Finally, it provides a Python script that imports and uses the generated message, along with a `mypy` command to verify type correctness.

mkdir -p project/proto project/output

cat <<EOF > project/proto/example.proto
syntax = "proto3";

package example;

message MyMessage {
  string name = 1;
  int32 id = 2;
  bool is_active = 3;
}
EOF

# Ensure protoc and protoc-gen-mypy are in PATH or specify full paths
# protoc --plugin=protoc-gen-mypy=/path/to/protoc-gen-mypy ...
protoc --python_out=project/output --mypy_out=project/output project/proto/example.proto

# Expected output will include example_pb2.py and example_pb2.pyi in project/output

cat <<EOF > project/main.py
from project.output import example_pb2

def process_message(msg: example_pb2.MyMessage) -> None:
    print(f"Processing: {msg.name} (ID: {msg.id}, Active: {msg.is_active})")

# Correct usage
my_msg = example_pb2.MyMessage(name="Test", id=123, is_active=True)
process_message(my_msg)

# Incorrect usage (mypy would catch this)
# invalid_msg = example_pb2.MyMessage(name=123, id="abc")
# process_message(invalid_msg)
EOF

# Run mypy to type-check the project
mypy project

view raw JSON →