Skip to Content
Binal

Custom Codecs

Separate Python and binary representations

from datetime import datetime, timezone
from typing import Annotated

from binal import BinaryModel, Codec, EvalScope, UInt32, UInt64


class TimestampCodec(Codec[datetime, int]):
    storage = UInt64

    def encode(self, value: datetime, scope: EvalScope, /) -> int:
        return int(value.timestamp())

    def decode(self, value: int, scope: EvalScope, /) -> datetime:
        return datetime.fromtimestamp(value, tz=timezone.utc)


Timestamp = Annotated[datetime, TimestampCodec()]


class Event(BinaryModel, byte_order="big"):
    id: UInt32
    timestamp: Timestamp

scope is a read-only mapping of the fields before this one and the context fields, so a codec that depends on another value reads it as scope["name"].