{"id":5586,"library":"betterproto","title":"Betterproto: A Protobuf & gRPC Library for Python","description":"Betterproto is a Python library that generates Python dataclasses, Protobuf serialization, and gRPC client/server stubs directly from `.proto` files. It aims to provide a more Pythonic interface than the official `protobuf` library. The current stable version is 1.2.5, but a 2.0.0 beta is under active development, introducing significant breaking changes and new features. Releases are somewhat irregular, with recent focus on the 2.0.0 branch.","status":"active","version":"1.2.5","language":"en","source_language":"en","source_url":"https://github.com/danielgtaylor/python-betterproto","tags":["protobuf","grpc","serialization","dataclasses","code-generation"],"install":[{"cmd":"pip install betterproto","lang":"bash","label":"Install stable version"},{"cmd":"pip install betterproto==2.0.0b7","lang":"bash","label":"Install latest beta (for v2.x features)"}],"dependencies":[{"reason":"Required for gRPC client/server functionality.","package":"grpclib","optional":true},{"reason":"Required for generating Pydantic dataclasses (available in 2.0.0b6+ with `--python_betterproto_opt=pydantic_dataclasses`).","package":"pydantic","optional":true}],"imports":[{"symbol":"Message","correct":"from betterproto import Message"},{"note":"For working with Protobuf enums.","symbol":"enum","correct":"import betterproto.enum"},{"note":"Used in generated code to define Protobuf fields.","symbol":"string_field","correct":"from betterproto import string_field"}],"quickstart":{"code":"import os\nfrom pathlib import Path\nimport subprocess\nimport sys\n\n# 1. Define a .proto file\nproto_content = \"\"\"\nsyntax = \"proto3\";\n\nmessage GreetRequest {\n  string name = 1;\n}\n\nmessage GreetResponse {\n  string greeting = 1;\n}\n\"\"\"\nproto_file_path = Path(\"greet.proto\")\nproto_file_path.write_text(proto_content)\n\n# 2. Compile the .proto file using protoc with betterproto plugin\n#    Ensure `protoc` is installed and in your PATH.\n#    The betterproto Python package ships its own protoc plugin.\n\ntry:\n    # Find the betterproto plugin\n    betterproto_plugin = next(\n        p for p in sys.path if 'betterproto' in p and 'site-packages' in p\n    ) + '/betterproto/plugin/protoc-gen-python_betterproto'\n\n    print(f\"Using betterproto plugin: {betterproto_plugin}\")\n\n    compile_command = [\n        \"protoc\",\n        f\"--plugin=protoc-gen-python_betterproto={betterproto_plugin}\",\n        \"--python_betterproto_out=.\",\n        str(proto_file_path)\n    ]\n    subprocess.run(compile_command, check=True, capture_output=True)\n    print(\"Proto file compiled successfully to greet.py\")\n\n    # 3. Use the generated Python code\n    from greet import GreetRequest, GreetResponse\n\n    request = GreetRequest(name=\"World\")\n    print(f\"Created request: {request.name}\")\n\n    # Serialize the message\n    serialized_data = bytes(request)\n    print(f\"Serialized data (bytes): {serialized_data}\")\n\n    # Deserialize the message\n    deserialized_request = GreetRequest().parse(serialized_data)\n    print(f\"Deserialized request: {deserialized_request.name}\")\n\n    response = GreetResponse(greeting=f\"Hello, {deserialized_request.name}!\")\n    print(f\"Created response: {response.greeting}\")\n\nexcept FileNotFoundError:\n    print(\"Error: 'protoc' command not found. Please install Protocol Buffers compiler.\")\nexcept subprocess.CalledProcessError as e:\n    print(f\"Error compiling proto file: {e.stderr.decode()}\")\nexcept ImportError:\n    print(\"Error: Could not import generated 'greet' module. Compilation might have failed or plugin path is incorrect.\")\nfinally:\n    # Clean up generated files\n    Path(\"greet.py\").unlink(missing_ok=True)\n    Path(\"greet.proto\").unlink(missing_ok=True)\n    print(\"Cleaned up temporary files.\")\n","lang":"python","description":"This quickstart demonstrates how to define a `.proto` file, compile it using `protoc` with the `betterproto` plugin, and then interact with the generated Python message classes. It covers basic message instantiation, serialization, and deserialization. Ensure the Protocol Buffers compiler (`protoc`) is installed and available in your system's PATH."},"warnings":[{"fix":"Upgrade Pydantic to version 2.x and ensure your betterproto generated code is also updated for Pydantic v2 compatibility. Pass `--python_betterproto_opt=pydantic_dataclasses` during compilation to enable Pydantic dataclasses.","message":"Betterproto v2.0.0b7+ drops support for Pydantic v1. If you use Pydantic dataclasses, you must upgrade to Pydantic v2.","severity":"breaking","affected_versions":"2.0.0b7+"},{"fix":"Refer to the betterproto documentation on how to properly check and access `oneof` fields using their `is_set` or `which_oneof` methods before direct access.","message":"In Betterproto v2.0.0b7+, attempting to access an unset `oneof` field will now raise an `AttributeError`. Previously, this might have returned a default value or `None` without explicit checking.","severity":"breaking","affected_versions":"2.0.0b7+"},{"fix":"Ensure your Python environment is running version 3.7 or higher when using betterproto v2.x.","message":"Betterproto v2.0.0b6+ requires Python 3.7 or newer. Earlier beta versions had different minimum Python requirements.","severity":"breaking","affected_versions":"2.0.0b6+"},{"fix":"Update client calls from `service.method(field1='val')` to `service.method(RequestMessage(field1='val'))` and adjust server handlers accordingly. This aligns with a more common gRPC pattern.","message":"In Betterproto v2.0.0b5+, gRPC client calls and server handlers now require input message fields to be explicitly wrapped in their respective message objects.","severity":"breaking","affected_versions":"2.0.0b5+"},{"fix":"Install `protoc` by following the official Protocol Buffers documentation for your operating system (e.g., via `apt`, `brew`, or downloading from GitHub releases).","message":"Betterproto is a code generator; you *must* have the `protoc` (Protocol Buffers compiler) executable installed and in your system's PATH to use it. `pip install betterproto` only installs the Python library and its `protoc` plugin, not `protoc` itself.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Be mindful of which version you are installing (`pip install betterproto` for 1.x, `pip install betterproto==2.0.0bX` for 2.x beta) and consult the release notes and upgrade guides for the specific version you intend to use.","message":"The `betterproto` library has two major versions currently active: stable `1.x` and an actively developed `2.x` beta. The `2.x` branch introduces many breaking changes and new features (like Pydantic v2 support, gRPC API changes, etc.).","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-10T00:00:00.000Z","next_check":"2026-07-09T00:00:00.000Z"}