Typing stubs for Protobuf

6.32.1.20260221 · active · verified Sat Mar 28

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

Install

Imports

Quickstart

This quickstart demonstrates how `types-protobuf` provides static type checking for code interacting with `google.protobuf` messages. It includes a simulated custom message type (which would typically be generated from a `.proto` file) and usage of a well-known type. With `types-protobuf` installed, type checkers can verify argument types, attribute access, and return types.

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}")

view raw JSON →