Typing stubs for grpcio
This library provides high-quality type stubs for the `grpcio` Python library, enabling static type checkers like MyPy to understand gRPC-related code. It's part of the `typeshed` project. The current version is 1.0.0.20260408, with releases typically following updates from the main `grpcio` library or the broader `typeshed` project, often on a monthly or bi-monthly basis.
Warnings
- gotcha Remember to install the `grpcio` runtime library itself. `types-grpcio` provides only type hints and is not a runtime dependency; your application will fail at runtime if `grpcio` is not installed.
- gotcha Using a `types-grpcio` version that is significantly older or newer than your `grpcio` runtime library can lead to incorrect type checking results, `mypy` errors, or missed type safety improvements.
- gotcha Type checking for your own gRPC generated code (from `.proto` files) requires additional configuration for `mypy`, often involving the `mypy-protobuf` plugin or `mypy`'s `--proto-path` flag. `types-grpcio` primarily covers the core `grpcio` library, not your specific service stubs.
Install
-
pip install types-grpcio
Imports
- grpc
import grpc
Quickstart
import grpc
from typing import cast
# To make this example runnable, you would typically have:
# 1. A .proto file defining a service (e.g., helloworld.proto)
# 2. Generated Python code for the service (e.g., helloworld_pb2.py, helloworld_pb2_grpc.py)
# using `python -m grpc_tools.protoc ...`
def demonstrate_typing():
# types-grpcio provides type hints for grpc functions and objects.
# For instance, `grpc.insecure_channel` is correctly typed.
channel: grpc.Channel = grpc.insecure_channel('localhost:50051')
print(f"Successfully created a gRPC channel: {type(channel).__name__}")
# With types-grpcio, static analysis tools like MyPy can verify
# that `channel` is indeed a `grpc.Channel` object and that its methods are correct.
# Example (would require generated stubs for full type checking):
# from helloworld_pb2_grpc import GreeterStub
# stub: GreeterStub = GreeterStub(channel)
# print("Type hints for gRPC stub are available.")
channel.close()
if __name__ == '__main__':
demonstrate_typing()
# To verify types with MyPy:
# 1. Ensure `grpcio`, `types-grpcio`, and `mypy` are installed:
# `pip install grpcio types-grpcio mypy`
# 2. Run MyPy on this file:
# `mypy your_script_name.py`
# MyPy should report no errors for the `grpc` types.