Semantic Types
UUIDs, network addresses, dates and times, complex and rational numbers
These are codecs over an integer, bytes, or tuple storage, so they follow the same rules as custom codecs: the storage value is validated, and a value the codec rejects raises EncodeError (or ValidationError when the storage value is out of range).
| Type | Python type | Wire format |
|---|---|---|
UUID | uuid.UUID | 16 bytes, RFC 4122 (big-endian) order |
GUID | uuid.UUID | 16 bytes, first three fields little-endian |
IPv4 | ipaddress.IPv4Address | 4 bytes, network order |
IPv6 | ipaddress.IPv6Address | 16 bytes, network order |
MAC | str ("aa:bb:cc:dd:ee:ff") | 6 bytes |
Complex64 | complex | real then imaginary, two Float32 |
Complex128 | complex | real then imaginary, two Float64 |
Timestamp(storage, unit) | aware datetime | whole units since 1970-01-01 UTC |
DateTime(storage, unit) | naive datetime | whole units since 1970-01-01 (wall clock) |
Date(storage) | date | days since 1970-01-01 |
Time(storage, unit) | naive time | whole units since midnight |
Duration(storage, unit) | timedelta | whole units |
Rational(numerator, denominator) | Fraction | numerator then positive denominator |
The first seven are ready aliases; the rest are codecs used as Annotated metadata, because their storage width and unit are part of each format. unit is "s", "ms", or "us". The defaults are Int64 seconds for Timestamp, DateTime, and Duration, Int32 days for Date, UInt32 milliseconds for Time, and Int32 / UInt32 for Rational.
A time value must be a whole number of units — a Timestamp in seconds rejects a datetime with microseconds rather than truncating it. Timestamp takes only aware datetimes and decodes to UTC; DateTime and Time take only naive values. MAC accepts : or - separators and decodes to lowercase with :. A Rational is stored in lowest terms, and a zero denominator on the wire is a DecodeError.
import ipaddress
import uuid
from datetime import UTC, datetime
from fractions import Fraction
from typing import Annotated
from binal import IPv4, MAC, UUID, BinaryModel, Rational, Timestamp, UInt32
class Lease(BinaryModel, byte_order="big"):
client: UUID
address: IPv4
hardware: MAC
expires: Annotated[datetime, Timestamp(UInt32)]
ratio: Annotated[Fraction, Rational()]
Lease(
client=uuid.UUID(int=1),
address=ipaddress.IPv4Address("10.0.0.7"),
hardware="aa:bb:cc:00:11:22",
expires=datetime(2030, 1, 1, tzinfo=UTC),
ratio=Fraction(3, 4),
).encode() The codec classes behind the aliases (UUIDCodec(layout), IPv4Codec, IPv6Codec, MACCodec, ComplexCodec(part)) are exported too, for a different part type such as ComplexCodec(Float16).