Google API Common Protos Type Stubs

2.3.1 · active · verified Thu Apr 16

The `googleapis-common-protos-stubs` library provides PEP 561-compliant type stubs for the `googleapis-common-protos` Python package. It enables static type checking tools like Mypy to understand the types provided by Google's common protocol buffer definitions, which are widely used across Google API services. The current version is 2.3.1, and it maintains an active release cadence, often aligning with updates to the underlying `googleapis-common-protos` or `mypy-protobuf` toolchain.

Common errors

Warnings

Install

Imports

Quickstart

To quickly verify `googleapis-common-protos-stubs` is working, create a Python file that imports a common protobuf type (e.g., `Timestamp`). Then, run `mypy` on this file, ensuring you include the `--namespace-packages` flag. This flag is critical for `mypy` to correctly discover types within the namespace package structure used by the stubs since version 2.0.0. The example demonstrates a simple function using `Timestamp` and the `mypy` command to check it.

import os
import subprocess

# A simple Python file using a common proto type
python_code = '''
from google.protobuf.timestamp_pb2 import Timestamp
from datetime import datetime

def create_timestamp_message(dt: datetime) -> Timestamp:
    timestamp = Timestamp()
    timestamp.FromDatetime(dt)
    return timestamp

def get_seconds(ts: Timestamp) -> int:
    return ts.seconds # type: ignore [attr-defined]

# Example usage (not type-checked for this demo, just for context)
# now = datetime.now()
# ts_msg = create_timestamp_message(now)
# print(f"Created Timestamp: {ts_msg.seconds}.{ts_msg.nanos}")
'''

with open('my_proto_app.py', 'w') as f:
    f.write(python_code)

# Run mypy with --namespace-packages to type-check
try:
    # Using `--namespace-packages` is crucial since v2.0.0 of the stubs
    result = subprocess.run(['mypy', '--namespace-packages', 'my_proto_app.py'], capture_output=True, text=True, check=True)
    print("Mypy successful:")
    print(result.stdout)
    print("Note: 'type: ignore' used for demonstration; in real code, you'd fix type errors.")
except subprocess.CalledProcessError as e:
    print(f"Mypy failed with errors:\n{e.stderr}")
finally:
    os.remove('my_proto_app.py')

view raw JSON →