Introduction to mypy-protobuf
mypy-protobuf is a powerful tool that enables static type checking for Protocol Buffers within Python. It integrates seamlessly with mypy
, the static type checker for Python, enhancing type safety and helping catch potential bugs early in the development cycle.
API Examples and Usage
Here, we explore various APIs provided by mypy-protobuf
and illustrate with code snippets.
Setting Up mypy-protobuf
pip install mypy-protobuf
After installation, you can convert your .proto files into Python files with type annotations.
Generating Python Code from .proto Files
protoc --python_out=. --mypy_out=. example.proto
This command generates Python code with type annotations from your Protocol Buffer definitions.
Defining a .proto File
syntax = "proto3"; package example; message User { string name = 1; int32 id = 2; string email = 3; }
Working with Generated Code
Once you’ve generated the Python code, you can use it with MyPy to check types:
from example_pb2 import User def get_user() -> User: return User(name="John", id=123, email="john@example.com")
Using mypy for Type Checking
def greet_user(user: User) -> str: return f"Hello, {user.name}!" user = get_user() print(greet_user(user))
Run mypy
to ensure type safety:
mypy script.py
Example Application Using mypy-protobuf
Below is an example of a simple application that demonstrates the power of type checking with mypy-protobuf
.
example.proto
syntax = "proto3"; package example; message Product { string name = 1; int32 id = 2; } message Order { int32 order_id = 1; repeated Product products = 2; }
Application Code
from example_pb2 import Product, Order def create_order(order_id: int, products: list[Product]) -> Order: return Order(order_id=order_id, products=products) def main() -> None: product1 = Product(name="Product1", id=1) product2 = Product(name="Product2", id=2) order = create_order(101, [product1, product2]) print(f"Order ID: {order.order_id}, Products: {[p.name for p in order.products]}") if __name__ == "__main__": main()
Ensure type safety by running mypy
:
mypy app.py
This example showcases the benefits of type-checking in improving code reliability and reducing runtime errors with the help of mypy-protobuf
.
Hash: 7f301c47dfd8a28d5d2b6f63eef1ff684acbfdf321adfdfcda2edebe9bc5f98b