Skip to content

from dataclasses import dataclassfrom pure_protobuf.message import BaseMessage

Well-known types

pure_protobuf.well_known module provides message definitions for some well-known types.

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 conventionally define message classes and make them importable (similarly to the pickle behaviour):

test_any.py
from dataclasses import dataclass
from typing import Annotated

from pure_protobuf.annotations import Field
from pure_protobuf.message import BaseMessage
from pure_protobuf.well_known import Any_

# The class must be importable:
# @dataclass
# class ChildMessage(BaseMessage):
#     foo: Annotated[int, Field(1)]

from tests.test_well_known import ChildMessage


child = ChildMessage(foo=42)
any_ = Any_.from_message(child)
assert any_.type_url.geturl() == "import://tests.test_well_known/ChildMessage"
assert any_.into_message() == child


@dataclass
class ParentMessage(BaseMessage):
    children: Annotated[list[Any_], Field(1)]


parent = ParentMessage(children=[any_])
assert ParentMessage.loads(parent.dumps()) == parent

Type URL format

Please, consider the URL format a part of the public API. This means, in particular, that future major version bumps may change the format in a backwards-incompatible way.

Timestamp

Implements the Timestamp well-known type and supports conversion from and to datetime.

from_datetime classmethod

from_datetime(value: datetime) -> Timestamp

Convert the datetime to Timestamp.

into_datetime

into_datetime() -> datetime

Convert to datetime.

Duration

Implements the Duration well-known type.

from_timedelta classmethod

from_timedelta(value: timedelta) -> Duration

Convert the timedelta into Duration.

into_timedelta

into_timedelta() -> timedelta

Convert into timedelta.