English · Русский
Documentation · PyPI · Telegram
Typed Python models for sequential binary formats. Keep the wire layout explicit while working with ordinary Python objects; bytespec reads and writes the fields and tracks lengths and offsets.
from bytespec import ProtoModel
class User(ProtoModel):
name: str
active: bool
user = User(name="Anna", active=True)
encoded = user.encode()
decoded = User.decode(encoded)
assert decoded == userThe default header is used automatically. You only need to set __header__
when your format requires a different layout.
For an existing protocol, choose the header elements and field representations:
from bytespec import Constructor, Flags, PayloadLength, ProtoModel, field
from bytespec.types import UInt32
class Packet(ProtoModel):
__constructor__ = 0x1234
__header__ = (Constructor(2), Flags(1), PayloadLength(2))
user_id: UInt32
name: str | None = field(flag=0, prefix_length=1)
packet = Packet(user_id=42, name="Anna")
assert Packet.decode(packet.encode()) == packetConstructor identifies the message, Flags marks present optional fields,
and PayloadLength records the total byte length of all fields. bytespec computes the
flags and lengths; UInt32 and field() define the field representation.
bytespec fits custom or existing sequential binary formats when you want
typed models without a separate schema language or code generation.
It supports lists, nested models, optional fields, IntEnum, UUID, datetime,
numeric representations, and custom codecs.
Other tools serve different needs:
- Construct — a powerful binary parser/builder DSL.
- msgspec — standard formats such as JSON and MessagePack.
- Protobuf — a schema/compiler ecosystem with its own wire format.
- struct — small, fixed structures.
Why bytespec? explains the tradeoffs and shows the same packet in struct, Construct, and bytespec.
Python 3.10+:
pip install bytespecOr uv add bytespec.
The full guide and API reference are available at bytespec.pymax.org in Russian and English.
Take a known packet from your protocol, describe a few fields, and compare the re-encoded result with the original bytes. That is a useful first check of whether the library fits your format.
Questions, ideas and feedback are welcome in the Telegram community.