gRPC Mypy Stubs

1.53.0.6 · active · verified Fri Apr 10

grpc-stubs provides high-quality Mypy stubs for the gRPC Python library (`grpcio`). It enables static type checking for gRPC client and server code, significantly improving code reliability and maintainability. The current version is 1.53.0.6, which tracks `grpcio` releases, with updates typically coinciding with `grpcio` major versions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a simplified gRPC client using placeholder types to represent code typically generated by `grpcio-tools`. `grpc-stubs` provides the necessary type hints for `grpc.Channel`, generated `_grpc.py` stubs, and other `grpcio` components, enabling tools like Mypy to perform static analysis on your gRPC client and server code. To run this, install `grpcio`, `mypy`, and `grpc-stubs` and then execute `mypy your_script_name.py`.

import grpc

# In a real project, these would be generated from your .proto files by grpcio-tools:
# from your_project import greeter_pb2 as pb2
# from your_project import greeter_pb2_grpc as pb2_grpc

# For this example, we'll use placeholder types to make it runnable.
class HelloRequest:
    def __init__(self, name: str):
        self.name = name
class HelloReply:
    def __init__(self, message: str):
        self.message = message
class GreeterStub:
    # This __init__ signature and method signature are what grpc-stubs would type.
    def __init__(self, channel: grpc.Channel):
        self._channel = channel
    def SayHello(self, request: HelloRequest, timeout: float = None) -> HelloReply:
        # Simulate a network call
        print(f"Simulating gRPC call for: {request.name}")
        return HelloReply(message=f"Hello, {request.name}!")

def run_client():
    # grpc-stubs provides types for the `grpc` module itself, like `insecure_channel`
    with grpc.insecure_channel('localhost:50051') as channel:
        # And also for generated stubs like GreeterStub
        stub: GreeterStub = GreeterStub(channel)
        
        # This interaction is now type-checked by mypy thanks to grpc-stubs
        request = HelloRequest(name="Mypy User")
        response: HelloReply = stub.SayHello(request, timeout=5.0)
        
        print(f"Client received: {response.message}")

        # Example of a type error that mypy would catch:
        # stub.SayHello(HelloRequest(name=123)) # Mypy would flag `name` as int, expected str

if __name__ == '__main__':
    run_client()
    print("\nTo enable type checking for this code:")
    print("1. Ensure you have `grpcio`, `mypy`, and `grpc-stubs` installed:")
    print("   pip install grpcio mypy grpc-stubs")
    print("2. Run mypy on your script:")
    print("   mypy your_script_name.py")

view raw JSON →