Afterwards, commits up to (and including) 124613f55fa8ff62a460e1ad33c5c78723b703a0 on python-betterproto, have been cherry-picked.
Changes in this project compared with the base project:
Renamed to aristaproto.
Cut support for Python < 3.10.
Updating various CI actions and dependencies.
Merged docs from multiple rst files to MarkDown.
Keep nanosecond precision for Timestamp.
Subclass datetime to store the original nano-second value when converting from Timestamp to datetime.
On conversion from the subclass of datetime to Timestamp the original nano-second value is restored.
Minor fixes.
Escaping double-quotes in docstrings.
Installation
First, install the package. Note that the [compiler] feature flag tells it to install extra dependencies only needed by the protoc plugin:
# Install both the library and compiler
pip install "aristaproto[compiler]"
# Install just the library (to use the generated code output)
pip install aristaproto
Getting Started
Compiling proto files
Given you installed the compiler and have a proto file, e.g example.proto:
syntax = "proto3";
package hello;
// Greeting represents a message you can tell a user.
message Greeting {
string message = 1;
}
You can run the following to invoke protoc directly:
This will generate lib/hello/__init__.py which looks like:
# Generated by the protocol buffer compiler. DO NOT EDIT!
# sources: example.proto
# plugin: python-aristaproto
from dataclasses import dataclass
import aristaproto
@dataclass
class Greeting(aristaproto.Message):
"""Greeting represents a message you can tell a user."""
message: str = aristaproto.string_field(1)
Now you can use it!
>>> from lib.hello import Greeting
>>> test = Greeting()
>>> test
Greeting(message='')
>>> test.message = "Hey!"
>>> test
Greeting(message="Hey!")
>>> serialized = bytes(test)
>>> serialized
b'\n\x04Hey!'
>>> another = Greeting().parse(serialized)
>>> another
Greeting(message="Hey!")
>>> another.to_dict()
{"message": "Hey!"}
>>> another.to_json(indent=2)
'{\n "message": "Hey!"\n}'
Async gRPC Support
The generated Protobuf Message classes are compatible with 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.
Given an example service definition:
syntax = "proto3";
package echo;
message EchoRequest {
string value = 1;
// Number of extra times to echo
uint32 extra_times = 2;
}
message EchoResponse {
repeated string values = 1;
}
message EchoStreamResponse {
string value = 1;
}
service Echo {
rpc Echo(EchoRequest) returns (EchoResponse);
rpc EchoStream(EchoRequest) returns (stream EchoStreamResponse);
}
This project also produces server-facing stubs that can be used to implement a Python
gRPC server.
To use them, simply subclass the base class in the generated files and override the
service methods:
import asyncio
from echo import EchoBase, EchoRequest, EchoResponse, EchoStreamResponse
from grpclib.server import Server
from typing import AsyncIterator
class EchoService(EchoBase):
async def echo(self, echo_request: "EchoRequest") -> "EchoResponse":
return EchoResponse(
[echo_request.value for _ in range(echo_request.extra_times)]
)
async def echo_stream(
self, echo_request: "EchoRequest"
) -> AsyncIterator["EchoStreamResponse"]:
for _ in range(echo_request.extra_times):
yield EchoStreamResponse(echo_request.value)
async def main():
server = Server([EchoService()])
await server.start("127.0.0.1", 50051)
await server.wait_closed()
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
JSON
Both serializing and parsing are supported to/from JSON and Python dictionaries using the following methods:
Sometimes 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.
Use aristaproto.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.
# Old way (official Google Protobuf package)
>>> mymessage.HasField('myfield')
# New way (this project)
>>> aristaproto.serialized_on_wire(mymessage.myfield)
One-of Support
Protobuf 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:
syntax = "proto3";
message Test {
oneof foo {
bool on = 1;
int32 count = 2;
string name = 3;
}
}
On Python 3.10 and later, you can use a match statement to access the provided one-of field, which supports type-checking:
test = Test()
match test:
case Test(on=value):
print(value) # value: bool
case Test(count=value):
print(value) # value: int
case Test(name=value):
print(value) # value: str
case _:
print("No value provided")
You can also use aristaproto.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.
>>> test = Test()
>>> aristaproto.which_one_of(test, "foo")
["", None]
>>> test.on = True
>>> aristaproto.which_one_of(test, "foo")
["on", True]
# Setting one member of the group resets the others.
>>> test.count = 57
>>> aristaproto.which_one_of(test, "foo")
["count", 57]
# Default (zero) values also work.
>>> test.name = ""
>>> aristaproto.which_one_of(test, "foo")
["name", ""]
Again this is a little different than the official Google code generator:
# Old way (official Google protobuf package)
>>> message.WhichOneof("group")
"foo"
# New way (this project)
>>> aristaproto.which_one_of(message, "group")
["foo", "foo's value"]
Well-Known Google Types
Google 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:
For 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:
You can use python-aristaproto to generate pydantic based models, using
pydantic dataclasses. This means the results of the protobuf unmarshalling will
be typed checked. The usage is the same, but you need to add a custom option
when calling the protobuf compiler:
With the important change being --python_aristaproto_opt=pydantic_dataclasses. This will
swap the dataclass implementation from the builtin python dataclass to the
pydantic dataclass. You must have pydantic as a dependency in your project for
this to work.
Configuration typing imports
By 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:
Python 3.11+ for the full development toolchain. Runtime, generation, and tests
support Python 3.10+.
uv manages Python
environments and installs dependencies from uv.lock. The required uv version
is declared in pyproject.toml.
poethepoet provides the development tasks
defined in pyproject.toml. It is installed with the default dev group; invoke
tasks with uv run --locked poe.
Setup
# Install the locked development, compiler, test, and lint dependencies
uv sync --locked --python 3.11
Code style
This project uses Ruff for Python formatting and linting.
Before committing changes run:
uv run --locked poe format
CI checks formatting and linting with the pinned pre-commit hooks.
Tests
There are two types of tests:
Standard tests
Custom tests
Standard tests
Adding a standard test case is easy.
Create a new directory aristaproto/tests/inputs/<name>
add <name>.proto with a message called Test
add <name>.json with some test data (optional)
It will be picked up automatically when you run the tests.
Custom tests are found in tests/test_*.py and are run with pytest.
Running
Here's how to run the tests.
# Generate assets from sample .proto files required by the tests
uv run --locked poe generate
# Run the tests
uv run --locked poe test
To generate fixtures and run the full suite on Python 3.10–3.15 in isolated
environments, using the same locked compiler/test groups as CI, run:
uv run --locked poe full-test
To select specific Python versions, invoke the runner directly:
uv run --locked python -m tests.run_all 3.10 3.15
The compiler and test dependency groups support Python 3.10+. The default
dev group includes them alongside the lint group and development tools that
require Python 3.11+. CI selects only the groups needed by each job and installs
third-party dependencies from wheels with uv sync --locked --no-build.
(Re)compiling Google Well-known Types
Aristaproto includes compiled versions for Google's well-known types at src/aristaproto/lib/google.
Be sure to regenerate these files when modifying the plugin output format, and validate by running the tests.
Normally, 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.
Assuming your google.protobuf source files (included with all releases of protoc) are located in /usr/local/include, you can regenerate them as follows: