{"id":13461688,"url":"https://github.com/danielgtaylor/python-betterproto","last_synced_at":"2025-05-12T13:24:32.869Z","repository":{"id":37612010,"uuid":"214084028","full_name":"danielgtaylor/python-betterproto","owner":"danielgtaylor","description":"Clean, modern, Python 3.6+ code generator \u0026 library for Protobuf 3 and async gRPC","archived":false,"fork":false,"pushed_at":"2025-04-22T11:53:51.000Z","size":1310,"stargazers_count":1683,"open_issues_count":175,"forks_count":228,"subscribers_count":23,"default_branch":"master","last_synced_at":"2025-05-11T17:02:50.195Z","etag":null,"topics":["asyncio","code-generator","grpc","plugin","protocol-buffer-compiler","python-3"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/danielgtaylor.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":".github/CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2019-10-10T04:09:03.000Z","updated_at":"2025-05-09T22:45:44.000Z","dependencies_parsed_at":"2023-01-29T19:02:48.884Z","dependency_job_id":"cce02b9a-48c8-4ff7-994b-cb50138d901a","html_url":"https://github.com/danielgtaylor/python-betterproto","commit_stats":{"total_commits":380,"total_committers":83,"mean_commits":4.578313253012048,"dds":0.7078947368421052,"last_synced_commit":"34b8249b91b2788432a7326fdf40b3f99798b5c8"},"previous_names":[],"tags_count":16,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danielgtaylor%2Fpython-betterproto","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danielgtaylor%2Fpython-betterproto/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danielgtaylor%2Fpython-betterproto/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danielgtaylor%2Fpython-betterproto/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/danielgtaylor","download_url":"https://codeload.github.com/danielgtaylor/python-betterproto/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253745849,"owners_count":21957453,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["asyncio","code-generator","grpc","plugin","protocol-buffer-compiler","python-3"],"created_at":"2024-07-31T11:00:52.528Z","updated_at":"2025-05-12T13:24:32.849Z","avatar_url":"https://github.com/danielgtaylor.png","language":"Python","readme":"# Better Protobuf / gRPC Support for Python\n\n![](https://github.com/danielgtaylor/python-betterproto/actions/workflows/ci.yml/badge.svg)\n\n\u003e :octocat: If you're reading this on github, please be aware that it might mention unreleased features! See the latest released README on [pypi](https://pypi.org/project/betterproto/).\n\nThis project aims to provide an improved experience when using Protobuf / gRPC in a modern Python environment by making use of modern language features and generating readable, understandable, idiomatic Python code. It will not support legacy features or environments (e.g. Protobuf 2). The following are supported:\n\n- Protobuf 3 \u0026 gRPC code generation\n  - Both binary \u0026 JSON serialization is built-in\n- Python 3.7+ making use of:\n  - Enums\n  - Dataclasses\n  - `async`/`await`\n  - Timezone-aware `datetime` and `timedelta` objects\n  - Relative imports\n  - Mypy type checking\n- [Pydantic Models](https://docs.pydantic.dev/) generation (see [Generating pydantic models](#generating-pydantic-models))\n\nThis project is heavily inspired by, and borrows functionality from:\n\n- https://github.com/protocolbuffers/protobuf/tree/master/python\n- https://github.com/eigenein/protobuf/\n- https://github.com/vmagamedov/grpclib\n\n## Motivation\n\nThis project exists because I am unhappy with the state of the official Google protoc plugin for Python.\n\n- No `async` support (requires additional `grpclib` plugin)\n- No typing support or code completion/intelligence (requires additional `mypy` plugin)\n- No `__init__.py` module files get generated\n- Output is not importable\n  - Import paths break in Python 3 unless you mess with `sys.path`\n- Bugs when names clash (e.g. `codecs` package)\n- Generated code is not idiomatic\n  - Completely unreadable runtime code-generation\n  - Much code looks like C++ or Java ported 1:1 to Python\n  - Capitalized function names like `HasField()` and `SerializeToString()`\n  - Uses `SerializeToString()` rather than the built-in `__bytes__()`\n  - Special wrapped types don't use Python's `None`\n  - Timestamp/duration types don't use Python's built-in `datetime` module\n\n\nThis project is a reimplementation from the ground up focused on idiomatic modern Python to help fix some of the above. While it may not be a 1:1 drop-in replacement due to changed method names and call patterns, the wire format is identical.\n\n## Installation\n\nFirst, install the package. Note that the `[compiler]` feature flag tells it to install extra dependencies only needed by the `protoc` plugin:\n\n```sh\n# Install both the library and compiler\npip install \"betterproto[compiler]\"\n\n# Install just the library (to use the generated code output)\npip install betterproto\n```\n\n*Betterproto* is under active development. To install the latest beta version, use `pip install --pre betterproto`.\n\n## Getting Started\n\n### Compiling proto files\n\nGiven you installed the compiler and have a proto file, e.g `example.proto`:\n\n```protobuf\nsyntax = \"proto3\";\n\npackage hello;\n\n// Greeting represents a message you can tell a user.\nmessage Greeting {\n  string message = 1;\n}\n```\n\nYou can run the following to invoke protoc directly:\n\n```sh\nmkdir lib\nprotoc -I . --python_betterproto_out=lib example.proto\n```\n\nor run the following to invoke protoc via grpcio-tools:\n\n```sh\npip install grpcio-tools\npython -m grpc_tools.protoc -I . --python_betterproto_out=lib example.proto\n```\n\nThis will generate `lib/hello/__init__.py` which looks like:\n\n```python\n# Generated by the protocol buffer compiler.  DO NOT EDIT!\n# sources: example.proto\n# plugin: python-betterproto\nfrom dataclasses import dataclass\n\nimport betterproto\n\n\n@dataclass\nclass Greeting(betterproto.Message):\n    \"\"\"Greeting represents a message you can tell a user.\"\"\"\n\n    message: str = betterproto.string_field(1)\n```\n\nNow you can use it!\n\n```python\n\u003e\u003e\u003e from lib.hello import Greeting\n\u003e\u003e\u003e test = Greeting()\n\u003e\u003e\u003e test\nGreeting(message='')\n\n\u003e\u003e\u003e test.message = \"Hey!\"\n\u003e\u003e\u003e test\nGreeting(message=\"Hey!\")\n\n\u003e\u003e\u003e serialized = bytes(test)\n\u003e\u003e\u003e serialized\nb'\\n\\x04Hey!'\n\n\u003e\u003e\u003e another = Greeting().parse(serialized)\n\u003e\u003e\u003e another\nGreeting(message=\"Hey!\")\n\n\u003e\u003e\u003e another.to_dict()\n{\"message\": \"Hey!\"}\n\u003e\u003e\u003e another.to_json(indent=2)\n'{\\n  \"message\": \"Hey!\"\\n}'\n```\n\n### Async gRPC Support\n\nThe generated Protobuf `Message` classes are compatible with [grpclib](https://github.com/vmagamedov/grpclib) so you are free to use it if you like. That said, this project also includes support for async gRPC stub generation with better static type checking and code completion support. It is enabled by default.\n\nGiven an example service definition:\n\n```protobuf\nsyntax = \"proto3\";\n\npackage echo;\n\nmessage EchoRequest {\n  string value = 1;\n  // Number of extra times to echo\n  uint32 extra_times = 2;\n}\n\nmessage EchoResponse {\n  repeated string values = 1;\n}\n\nmessage EchoStreamResponse  {\n  string value = 1;\n}\n\nservice Echo {\n  rpc Echo(EchoRequest) returns (EchoResponse);\n  rpc EchoStream(EchoRequest) returns (stream EchoStreamResponse);\n}\n```\n\nGenerate echo proto file:\n\n```\npython -m grpc_tools.protoc -I . --python_betterproto_out=. echo.proto\n```\n\nA client can be implemented as follows:\n```python\nimport asyncio\nimport echo\n\nfrom grpclib.client import Channel\n\n\nasync def main():\n    channel = Channel(host=\"127.0.0.1\", port=50051)\n    service = echo.EchoStub(channel)\n    response = await service.echo(echo.EchoRequest(value=\"hello\", extra_times=1))\n    print(response)\n\n    async for response in service.echo_stream(echo.EchoRequest(value=\"hello\", extra_times=1)):\n        print(response)\n\n    # don't forget to close the channel when done!\n    channel.close()\n\n\nif __name__ == \"__main__\":\n    loop = asyncio.get_event_loop()\n    loop.run_until_complete(main())\n\n```\n\nwhich would output\n```python\nEchoResponse(values=['hello', 'hello'])\nEchoStreamResponse(value='hello')\nEchoStreamResponse(value='hello')\n```\n\nThis project also produces server-facing stubs that can be used to implement a Python\ngRPC server.\nTo use them, simply subclass the base class in the generated files and override the\nservice methods:\n\n```python\nimport asyncio\nfrom echo import EchoBase, EchoRequest, EchoResponse, EchoStreamResponse\nfrom grpclib.server import Server\nfrom typing import AsyncIterator\n\n\nclass EchoService(EchoBase):\n    async def echo(self, echo_request: \"EchoRequest\") -\u003e \"EchoResponse\":\n        return EchoResponse([echo_request.value for _ in range(echo_request.extra_times)])\n\n    async def echo_stream(self, echo_request: \"EchoRequest\") -\u003e AsyncIterator[\"EchoStreamResponse\"]:\n        for _ in range(echo_request.extra_times):\n            yield EchoStreamResponse(echo_request.value)\n\n\nasync def main():\n    server = Server([EchoService()])\n    await server.start(\"127.0.0.1\", 50051)\n    await server.wait_closed()\n\nif __name__ == '__main__':\n    loop = asyncio.get_event_loop()\n    loop.run_until_complete(main())\n```\n\n### JSON\n\nBoth serializing and parsing are supported to/from JSON and Python dictionaries using the following methods:\n\n- Dicts: `Message().to_dict()`, `Message().from_dict(...)`\n- JSON: `Message().to_json()`, `Message().from_json(...)`\n\nFor compatibility the default is to convert field names to `camelCase`. You can control this behavior by passing a casing value, e.g:\n\n```python\nMyMessage().to_dict(casing=betterproto.Casing.SNAKE)\n```\n\n### Determining if a message was sent\n\nSometimes it is useful to be able to determine whether a message has been sent on the wire. This is how the Google wrapper types work to let you know whether a value is unset, set as the default (zero value), or set as something else, for example.\n\nUse `betterproto.serialized_on_wire(message)` to determine if it was sent. This is a little bit different from the official Google generated Python code, and it lives outside the generated `Message` class to prevent name clashes. Note that it **only** supports Proto 3 and thus can **only** be used to check if `Message` fields are set. You cannot check if a scalar was sent on the wire.\n\n```py\n# Old way (official Google Protobuf package)\n\u003e\u003e\u003e mymessage.HasField('myfield')\n\n# New way (this project)\n\u003e\u003e\u003e betterproto.serialized_on_wire(mymessage.myfield)\n```\n\n### One-of Support\n\nProtobuf supports grouping fields in a `oneof` clause. Only one of the fields in the group may be set at a given time. For example, given the proto:\n\n```protobuf\nsyntax = \"proto3\";\n\nmessage Test {\n  oneof foo {\n    bool on = 1;\n    int32 count = 2;\n    string name = 3;\n  }\n}\n```\n\nOn Python 3.10 and later, you can use a `match` statement to access the provided one-of field, which supports type-checking:\n\n```py\ntest = Test()\nmatch test:\n    case Test(on=value):\n        print(value)  # value: bool\n    case Test(count=value):\n        print(value)  # value: int\n    case Test(name=value):\n        print(value)  # value: str\n    case _:\n        print(\"No value provided\")\n```\n\nYou can also use `betterproto.which_one_of(message, group_name)` to determine which of the fields was set. It returns a tuple of the field name and value, or a blank string and `None` if unset.\n\n```py\n\u003e\u003e\u003e test = Test()\n\u003e\u003e\u003e betterproto.which_one_of(test, \"foo\")\n[\"\", None]\n\n\u003e\u003e\u003e test.on = True\n\u003e\u003e\u003e betterproto.which_one_of(test, \"foo\")\n[\"on\", True]\n\n# Setting one member of the group resets the others.\n\u003e\u003e\u003e test.count = 57\n\u003e\u003e\u003e betterproto.which_one_of(test, \"foo\")\n[\"count\", 57]\n\n# Default (zero) values also work.\n\u003e\u003e\u003e test.name = \"\"\n\u003e\u003e\u003e betterproto.which_one_of(test, \"foo\")\n[\"name\", \"\"]\n```\n\nAgain this is a little different than the official Google code generator:\n\n```py\n# Old way (official Google protobuf package)\n\u003e\u003e\u003e message.WhichOneof(\"group\")\n\"foo\"\n\n# New way (this project)\n\u003e\u003e\u003e betterproto.which_one_of(message, \"group\")\n[\"foo\", \"foo's value\"]\n```\n\n### Well-Known Google Types\n\nGoogle provides several well-known message types like a timestamp, duration, and several wrappers used to provide optional zero value support. Each of these has a special JSON representation and is handled a little differently from normal messages. The Python mapping for these is as follows:\n\n| Google Message              | Python Type                              | Default                |\n| --------------------------- | ---------------------------------------- | ---------------------- |\n| `google.protobuf.duration`  | [`datetime.timedelta`][td]               | `0`                    |\n| `google.protobuf.timestamp` | Timezone-aware [`datetime.datetime`][dt] | `1970-01-01T00:00:00Z` |\n| `google.protobuf.*Value`    | `Optional[...]`                          | `None`                 |\n| `google.protobuf.*`         | `betterproto.lib.google.protobuf.*`      | `None`                 |\n\n[td]: https://docs.python.org/3/library/datetime.html#timedelta-objects\n[dt]: https://docs.python.org/3/library/datetime.html#datetime.datetime\n\nFor the wrapper types, the Python type corresponds to the wrapped type, e.g. `google.protobuf.BoolValue` becomes `Optional[bool]` while `google.protobuf.Int32Value` becomes `Optional[int]`. All of the optional values default to `None`, so don't forget to check for that possible state. Given:\n\n```protobuf\nsyntax = \"proto3\";\n\nimport \"google/protobuf/duration.proto\";\nimport \"google/protobuf/timestamp.proto\";\nimport \"google/protobuf/wrappers.proto\";\n\nmessage Test {\n  google.protobuf.BoolValue maybe = 1;\n  google.protobuf.Timestamp ts = 2;\n  google.protobuf.Duration duration = 3;\n}\n```\n\nYou can do stuff like:\n\n```py\n\u003e\u003e\u003e t = Test().from_dict({\"maybe\": True, \"ts\": \"2019-01-01T12:00:00Z\", \"duration\": \"1.200s\"})\n\u003e\u003e\u003e t\nTest(maybe=True, ts=datetime.datetime(2019, 1, 1, 12, 0, tzinfo=datetime.timezone.utc), duration=datetime.timedelta(seconds=1, microseconds=200000))\n\n\u003e\u003e\u003e t.ts - t.duration\ndatetime.datetime(2019, 1, 1, 11, 59, 58, 800000, tzinfo=datetime.timezone.utc)\n\n\u003e\u003e\u003e t.ts.isoformat()\n'2019-01-01T12:00:00+00:00'\n\n\u003e\u003e\u003e t.maybe = None\n\u003e\u003e\u003e t.to_dict()\n{'ts': '2019-01-01T12:00:00Z', 'duration': '1.200s'}\n```\n\n## Generating Pydantic Models\n\nYou can use python-betterproto to generate pydantic based models, using\npydantic dataclasses. This means the results of the protobuf unmarshalling will\nbe typed checked. The usage is the same, but you need to add a custom option\nwhen calling the protobuf compiler:\n\n\n```\nprotoc -I . --python_betterproto_opt=pydantic_dataclasses --python_betterproto_out=lib example.proto\n```\n\nWith the important change being `--python_betterproto_opt=pydantic_dataclasses`. This will\nswap the dataclass implementation from the builtin python dataclass to the\npydantic dataclass. You must have pydantic as a dependency in your project for\nthis to work.\n\n## Configuration typing imports\n\nBy default typing types will be imported directly from typing.  This sometimes can lead to issues in generation if types that are being generated conflict with the name.  In this case you can configure the way types are imported from 3 different options:\n\n### Direct\n```\nprotoc -I . --python_betterproto_opt=typing.direct --python_betterproto_out=lib example.proto\n```\nthis configuration is the default, and will import types as follows:\n```\nfrom typing import (\n  List,\n  Optional,\n  Union\n)\n...\nvalue: List[str] = []\nvalue2: Optional[str] = None\nvalue3: Union[str, int] = 1\n```\n### Root\n```\nprotoc -I . --python_betterproto_opt=typing.root --python_betterproto_out=lib example.proto\n```\nthis configuration loads the root typing module, and then access the types off of it directly:\n```\nimport typing\n...\nvalue: typing.List[str] = []\nvalue2: typing.Optional[str] = None\nvalue3: typing.Union[str, int] = 1\n```\n\n### 310\n```\nprotoc -I . --python_betterproto_opt=typing.310 --python_betterproto_out=lib example.proto\n```\nthis configuration avoid loading typing all together if possible and uses the python 3.10 pattern:\n```\n...\nvalue: list[str] = []\nvalue2: str | None = None\nvalue3: str | int = 1\n```\n\n## Development\n\n- _Join us on [Discord](https://discord.gg/DEVteTupPb)!_\n- _See how you can help \u0026rarr; [Contributing](.github/CONTRIBUTING.md)_\n\n### Requirements\n\n- Python (3.7 or higher)\n\n- [poetry](https://python-poetry.org/docs/#installation)\n  *Needed to install dependencies in a virtual environment*\n\n- [poethepoet](https://github.com/nat-n/poethepoet) for running development tasks as defined in pyproject.toml\n  - Can be installed to your host environment via `pip install poethepoet` then executed as simple `poe`\n  - or run from the poetry venv as `poetry run poe`\n\n### Setup\n\n```sh\n# Get set up with the virtual env \u0026 dependencies\npoetry install -E compiler\n\n# Activate the poetry environment\npoetry shell\n```\n\n### Code style\n\nThis project enforces [black](https://github.com/psf/black) python code formatting.\n\nBefore committing changes run:\n\n```sh\npoe format\n```\n\nTo avoid merge conflicts later, non-black formatted python code will fail in CI.\n\n### Tests\n\nThere are two types of tests:\n\n1. Standard tests\n2. Custom tests\n\n#### Standard tests\n\nAdding a standard test case is easy.\n\n- Create a new directory `betterproto/tests/inputs/\u003cname\u003e`\n  - add `\u003cname\u003e.proto`  with a message called `Test`\n  - add `\u003cname\u003e.json` with some test data (optional)\n\nIt will be picked up automatically when you run the tests.\n\n- See also: [Standard Tests Development Guide](tests/README.md)\n\n#### Custom tests\n\nCustom tests are found in `tests/test_*.py` and are run with pytest.\n\n#### Running\n\nHere's how to run the tests.\n\n```sh\n# Generate assets from sample .proto files required by the tests\npoe generate\n# Run the tests\npoe test\n```\n\nTo run tests as they are run in CI (with tox) run:\n\n```sh\npoe full-test\n```\n\n### (Re)compiling Google Well-known Types\n\nBetterproto includes compiled versions for Google's well-known types at [src/betterproto/lib/google](src/betterproto/lib/google).\nBe sure to regenerate these files when modifying the plugin output format, and validate by running the tests.\n\nNormally, the plugin does not compile any references to `google.protobuf`, since they are pre-compiled. To force compilation of `google.protobuf`, use the option `--custom_opt=INCLUDE_GOOGLE`.\n\nAssuming your `google.protobuf` source files (included with all releases of `protoc`) are located in `/usr/local/include`, you can regenerate them as follows:\n\n```sh\nprotoc \\\n    --plugin=protoc-gen-custom=src/betterproto/plugin/main.py \\\n    --custom_opt=INCLUDE_GOOGLE \\\n    --custom_out=src/betterproto/lib \\\n    -I /usr/local/include/ \\\n    /usr/local/include/google/protobuf/*.proto\n```\n\n### TODO\n\n- [x] Fixed length fields\n  - [x] Packed fixed-length\n- [x] Zig-zag signed fields (sint32, sint64)\n- [x] Don't encode zero values for nested types\n- [x] Enums\n- [x] Repeated message fields\n- [x] Maps\n  - [x] Maps of message fields\n- [x] Support passthrough of unknown fields\n- [x] Refs to nested types\n- [x] Imports in proto files\n- [x] Well-known Google types\n  - [ ] Support as request input\n  - [ ] Support as response output\n    - [ ] Automatically wrap/unwrap responses\n- [x] OneOf support\n  - [x] Basic support on the wire\n  - [x] Check which was set from the group\n  - [x] Setting one unsets the others\n- [ ] JSON that isn't completely naive.\n  - [x] 64-bit ints as strings\n  - [x] Maps\n  - [x] Lists\n  - [x] Bytes as base64\n  - [ ] Any support\n  - [x] Enum strings\n  - [x] Well known types support (timestamp, duration, wrappers)\n  - [x] Support different casing (orig vs. camel vs. others?)\n- [x] Async service stubs\n  - [x] Unary-unary\n  - [x] Server streaming response\n  - [x] Client streaming request\n- [x] Renaming messages and fields to conform to Python name standards\n- [x] Renaming clashes with language keywords\n- [x] Python package\n- [x] Automate running tests\n- [ ] Cleanup!\n\n## Community\n\nJoin us on [Discord](https://discord.gg/DEVteTupPb)!\n\n## License\n\nCopyright © 2019 Daniel G. Taylor\n\nhttp://dgt.mit-license.org/\n","funding_links":[],"categories":["Python","Language-Specific"],"sub_categories":["Python"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdanielgtaylor%2Fpython-betterproto","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdanielgtaylor%2Fpython-betterproto","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdanielgtaylor%2Fpython-betterproto/lists"}