Skip to content

Python implementation of Protocol Buffers with dataclass-based schemaʼs

License

Notifications You must be signed in to change notification settings

eigenein/protobuf

Repository files navigation

pure-protobuf

GitHub Workflow Status Code coverage PyPI - Downloads PyPI – Version PyPI – Python License

Wow! Such annotated! Very buffers!

Documentation

Documentation

Quick examples

.protodefinition

It's not needed forpure-protobuf,but for the sake of an example, let's consider the following definition:

syntax="proto3";

messageSearchRequest{
stringquery=1;
int32page_number=2;
int32result_per_page=3;
}

And here's the same viapure-protobuf:

fromdataclassesimportdataclass
fromioimportBytesIO

frompure_protobuf.annotationsimportField
frompure_protobuf.messageimportBaseMessage
fromtyping_extensionsimportAnnotated


@dataclass
classSearchRequest(BaseMessage):
query:Annotated[str,Field(1)]=""
page_number:Annotated[int,Field(2)]=0
result_per_page:Annotated[int,Field(3)]=0


request=SearchRequest(query="hello",page_number=1,result_per_page=10)
buffer=bytes(request)
assertbuffer==b "\x0A\x05hello\x10\x01\x18\x0A"
assertSearchRequest.read_from(BytesIO(buffer))==request
fromioimportBytesIO

frompure_protobuf.annotationsimportField
frompure_protobuf.messageimportBaseMessage
frompydanticimportBaseModel
fromtyping_extensionsimportAnnotated


classSearchRequest(BaseMessage,BaseModel):
query:Annotated[str,Field(1)]=""
page_number:Annotated[int,Field(2)]=0
result_per_page:Annotated[int,Field(3)]=0


request=SearchRequest(query="hello",page_number=1,result_per_page=10)
buffer=bytes(request)
assertbuffer==b "\x0A\x05hello\x10\x01\x18\x0A"
assertSearchRequest.read_from(BytesIO(buffer))==request