Typing stubs for Protobuf
types-protobuf provides type stub files for the `protobuf` (also known as `google-protobuf`) library. It allows type checkers like Mypy or Pyright to perform static analysis on Python code that uses Protocol Buffers, improving code quality and catching potential type errors. This package is part of the `typeshed` project and aims to provide accurate annotations for `protobuf~=6.32.1`.
Warnings
- breaking Changes in `.proto` schema definitions (e.g., field renumbering, removal, or type alteration) can lead to runtime deserialization failures and will cause type checking errors if not properly managed. This is a fundamental aspect of Protobuf evolution, and `types-protobuf` will reflect these underlying API changes.
- gotcha `types-protobuf` is a partial stub package, meaning not all annotations for the `protobuf` library might be present. You might encounter `Missing type annotation` errors for some less common parts of the API.
- gotcha A mismatch between the installed `types-protobuf` version and the `protobuf` runtime library version can lead to incorrect type checking results. The stubs are generated against specific runtime versions (e.g., `protobuf~=6.32.1`).
- gotcha The handling of `Optional[type]` for protobuf wrapper classes (like `StringValue` or `Int32Value`) can be a source of type errors. In older `proto3` definitions or with specific `mypy-protobuf` configurations, values like `StringValue(value=None)` might pass at runtime but fail type checking if the stub expects `str` instead of `Optional[str]`.
Install
-
pip install types-protobuf
Imports
- Message
from google.protobuf import message
- Timestamp
from google.protobuf.timestamp_pb2 import Timestamp
Quickstart
import os
from google.protobuf.timestamp_pb2 import Timestamp # A well-known type
# --- Simulate generated _pb2.py content for a custom message ---
# In a real scenario, this would come from `my_message_pb2.py`
# generated by `protoc --python_out=. my_message.proto`
# my_message.proto content:
# syntax = "proto3";
# package mypackage;
# message MyMessage {
# string name = 1;
# int32 id = 2;
# repeated string tags = 3;
# }
# Simplified representation for quickstart (type checkers would use real stubs)
class MyMessage:
name: str
id: int
tags: list[str]
def __init__(self, name: str = '', id: int = 0, tags: list[str] | None = None) -> None:
self.name = name
self.id = id
self.tags = tags if tags is not None else []
def SerializeToString(self) -> bytes:
return b""
@classmethod
def ParseFromString(cls, serialized_data: bytes) -> 'MyMessage':
return cls()
# --- End simulated content ---
def process_message(msg: MyMessage) -> str:
"""Processes a custom protobuf message with type hints."""
print(f"Processing Message: Name={msg.name}, ID={msg.id}")
return f"Message with {len(msg.tags)} tags processed."
def get_current_timestamp() -> Timestamp:
"""Gets the current UTC timestamp using google.protobuf.Timestamp."""
ts = Timestamp()
ts.GetCurrentTime()
return ts
# Example Usage:
my_instance = MyMessage(name="ExampleUser", id=42, tags=["dev", "python"])
result = process_message(my_instance)
print(result)
timestamp_obj = get_current_timestamp()
print(f"Current UTC Timestamp: {timestamp_obj}")