All Projects → eigenein → Protobuf

eigenein / Protobuf

Licence: mit
Python implementation of Protocol Buffers data types with dataclasses support

Programming Languages

python
139335 projects - #7 most used programming language

Projects that are alternatives of or similar to Protobuf

Protobuf Nim
Protobuf implementation in pure Nim that leverages the power of the macro system to not depend on any external tools
Stars: ✭ 90 (-10.89%)
Mutual labels:  protobuf, protocol-buffers, library
Protobuf
[Looking for new ownership] Protocol Buffers for Go with Gadgets
Stars: ✭ 4,998 (+4848.51%)
Mutual labels:  protobuf, protocol-buffers
Protobuf
A pure Elixir implementation of Google Protobuf
Stars: ✭ 442 (+337.62%)
Mutual labels:  protobuf, protocol-buffers
Protoreflect
Reflection (Rich Descriptors) for Go Protocol Buffers
Stars: ✭ 651 (+544.55%)
Mutual labels:  protobuf, protocol-buffers
Proto
parser for Google ProtocolBuffers definition
Stars: ✭ 359 (+255.45%)
Mutual labels:  protobuf, protocol-buffers
Protolock
Protocol Buffer companion tool. Track your .proto files and prevent changes to messages and services which impact API compatibility.
Stars: ✭ 394 (+290.1%)
Mutual labels:  protobuf, protocol-buffers
Pbf
A low-level, lightweight protocol buffers implementation in JavaScript.
Stars: ✭ 618 (+511.88%)
Mutual labels:  protocol-buffers, library
ppx deriving protobuf
A Protocol Buffers codec generator for OCaml
Stars: ✭ 76 (-24.75%)
Mutual labels:  protobuf, protocol-buffers
Protobuf Swift
Google ProtocolBuffers for Apple Swift
Stars: ✭ 925 (+815.84%)
Mutual labels:  protobuf, protocol-buffers
Protobuf
Go support for Google's protocol buffers
Stars: ✭ 8,111 (+7930.69%)
Mutual labels:  protobuf, protocol-buffers
Samay
Command line Time tracking and reporting. Built using Go(programming language) and protocol buffers.
Stars: ✭ 37 (-63.37%)
Mutual labels:  protobuf, protocol-buffers
Gunk
Modern frontend and syntax for Protocol Buffers
Stars: ✭ 305 (+201.98%)
Mutual labels:  protobuf, protocol-buffers
AndTTT
🎲 Simple tic tac toe game for Android
Stars: ✭ 15 (-85.15%)
Mutual labels:  protobuf, protocol-buffers
Kroto Plus
gRPC Kotlin Coroutines, Protobuf DSL, Scripting for Protoc
Stars: ✭ 400 (+296.04%)
Mutual labels:  protobuf, protocol-buffers
ocaml-pb-plugin
A protoc plugin for generating OCaml code from protobuf (.proto) files.
Stars: ✭ 18 (-82.18%)
Mutual labels:  protobuf, protocol-buffers
Prototool
Your Swiss Army Knife for Protocol Buffers
Stars: ✭ 4,932 (+4783.17%)
Mutual labels:  protobuf, protocol-buffers
nimpb
Protocol Buffers for Nim
Stars: ✭ 29 (-71.29%)
Mutual labels:  protobuf, protocol-buffers
rails-microservices-book
A guide to building distributed Ruby on Rails applications using Protocol Buffers, NATS and RabbitMQ
Stars: ✭ 23 (-77.23%)
Mutual labels:  protobuf, protocol-buffers
Go Proto Validators
Generate message validators from .proto annotations.
Stars: ✭ 713 (+605.94%)
Mutual labels:  protobuf, protocol-buffers
Protocol Buffers Language Server
[WIP] Protocol Buffers Language Server
Stars: ✭ 44 (-56.44%)
Mutual labels:  protobuf, protocol-buffers

pure-protobuf

Python implementation of Protocol Buffers data types.

Build Status Coverage Status PyPI - Downloads PyPI – Version PyPI – Python License

Dataclasses

pure-protobuf allows you to take advantages of the standard dataclasses module to define message types. It is preferred over the legacy interface for new projects. The dataclasses interface is available in Python 3.6 and higher.

The legacy interface is deprecated and still available via pure_protobuf.legacy.

This guide describes how to use pure-protobuf to structure your data. It tries to follow the standard developer guide. It also assumes that you're familiar with Protocol Buffers.

Defining a message type

Let's look at the simple example. Here's how it looks like in proto3 syntax:

syntax = "proto3";

message SearchRequest {
  string query = 1;
  int32 page_number = 2;
  int32 result_per_page = 3;
}

And this is how you define it with pure-protobuf:

from dataclasses import dataclass

from pure_protobuf.dataclasses_ import field, message
from pure_protobuf.types import int32


@message
@dataclass
class SearchRequest:
    query: str = field(1, default='')
    page_number: int32 = field(2, default=int32(0))
    result_per_page: int32 = field(3, default=int32(0))
   

assert SearchRequest(
    query='hello',
    page_number=int32(1),
    result_per_page=int32(10),
).dumps() == b'\x0A\x05hello\x10\x01\x18\x0A'

Keep in mind that @message decorator must stay on top of @dataclass.

Serializing

Each class wrapped with @message gets two methods attached:

  • dumps() -> bytes to serialize message into a byte string
  • dump(io: IO) to serialize message into a file-like object

Deserializing

Each classes wrapped with @message gets two class methods attached:

  • loads(bytes_: bytes) -> TMessage to deserialize a message from a byte string
  • load(io: IO) -> TMessage to deserialize a message from a file-like object

These methods are also available as standalone functions in pure_protobuf.dataclasses_:

  • load(cls: Type[T], io: IO) -> T
  • loads(cls: Type[T], bytes_: bytes) -> T

Specifying field types

In pure-protobuf types are specified with type hints. Native Python float, str, bytes and bool types are supported. Since other Protocol Buffers types don't exist as native Python types, the package uses NewType to define them. They're available via pure_protobuf.types and named in the same way.

Assigning field numbers

Field numbers are provided via the metadata parameter of the field function: field(..., metadata={'number': number}). However, to improve readability and save some characters, pure-protobuf provides a helper function pure_protobuf.dataclasses_.field which accepts field number as the first positional parameter and just passes it to the standard field function.

Specifying field rules

typing.List and typing.Iterable annotations are automatically converted to repeated fields. Repeated fields of scalar numeric types use packed encoding by default:

from dataclasses import dataclass
from typing import List

from pure_protobuf.dataclasses_ import field, message
from pure_protobuf.types import int32


@message
@dataclass
class Message:
    foo: List[int32] = field(1, default_factory=list)

It's also possible to wrap a field type with typing.Optional. If None is assigned to an Optional field, then the field will be skipped during serialization.

Default values

In pure-protobuf it's developer's responsibility to take care of default values. If encoded message does not contain a particular element, the corresponding field stays unassigned. It means that the standard default and default_factory parameters of the field function work as usual:

from dataclasses import dataclass
from typing import Optional

from pure_protobuf.dataclasses_ import field, message
from pure_protobuf.types import int32


@message
@dataclass
class Foo:
    bar: int32 = field(1, default=42)
    qux: Optional[int32] = field(2, default=None)


assert Foo().dumps() == b'\x08\x2A'
assert Foo.loads(b'') == Foo(bar=42)

In fact, the pattern qux: Optional[int32] = field(2, default=None) is so common that there's a convenience function optional_field to define an Optional field with None value by default:

from dataclasses import dataclass
from typing import Optional

from pure_protobuf.dataclasses_ import optional_field, message
from pure_protobuf.types import int32


@message
@dataclass
class Foo:
    qux: Optional[int32] = optional_field(2)


assert Foo().dumps() == b''
assert Foo.loads(b'') == Foo(qux=None)

Enumerations

Subclasses of the standard IntEnum class are supported:

from dataclasses import dataclass
from enum import IntEnum

from pure_protobuf.dataclasses_ import field, message


class TestEnum(IntEnum):
    BAR = 1


@message
@dataclass
class Test:
    foo: TestEnum = field(1)


assert Test(foo=TestEnum.BAR).dumps() == b'\x08\x01'
assert Test.loads(b'\x08\x01') == Test(foo=TestEnum.BAR)

Using other message types

Embedded messages are defined the same way as normal dataclasses:

from dataclasses import dataclass

from pure_protobuf.dataclasses_ import field, message
from pure_protobuf.types import int32


@message
@dataclass
class Test1:
    a: int32 = field(1, default=0)


@message
@dataclass
class Test3:
    c: Test1 = field(3, default_factory=Test1)


assert Test3(c=Test1(a=int32(150))).dumps() == b'\x1A\x03\x08\x96\x01'

Well-known message types

pure_protobuf.google also provides built-in definitions for the following well-known message types:

Annotation pure_protobuf.types.google .proto
datetime Timestamp Timestamp
timedelta Duration Duration
typing.Any Any_ Any

They're handled automatically, you have nothing to do but use them normally in type hints:

from dataclasses import dataclass
from datetime import datetime
from typing import Optional

from pure_protobuf.dataclasses_ import field, message


@message
@dataclass
class Test:
    timestamp: Optional[datetime] = field(1, default=None)

Any

Since pure-protobuf is not able to download or parse .proto definitions, it provides a limited implementation of the Any message type. That is, you still have to define all message classes in the usual way. Then, pure-protobuf will be able to import and instantiate an encoded value:

from dataclasses import dataclass
from typing import Any, Optional

from pure_protobuf.dataclasses_ import field, message
from pure_protobuf.types.google import Timestamp


@message
@dataclass
class Message:
    value: Optional[Any] = field(1)


# Here `Timestamp` is used just as an example, in principle any importable user type works.
message = Message(value=Timestamp(seconds=42))
assert Message.loads(message.dumps()) == message
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].