ADR 0015: bytes values: a pointer and a length¶
Status: Final
Type: Feature
Created: 2026-07-28
Amends: 0014 (appends IR16: an arithmetic operand is a value promotion is defined over)
Related-ADRs: 0004 and 0025 (the Str whose representation a bytes shares), 0026 (the ownership discipline it follows), 0043 (encode and decode), 0016 (pygo.net, the first consumer), 0029, 0030 and 0066 (a bytes as a union case, a container member and an optional). Provenance: arbitrations A3, A12, A13, A45, A174; upstream question U13.
Context¶
pygo.net (ADR 0016) makes a compiled pygo program serve TCP, and sockets deal in bytes; until this ADR the compiler refused b"..." outright and postyp.Bytes was declared with no lowering behind it. This ADR first fixed the type to what a socket needs. Binary files, bytes fields, bytes in unions and containers then waited on a bytes that is released, and eight Shed Skin census programs waited on those, so on 2026-10-29 the owner decided that a bytes is represented as a Str is (A174).
Decision¶
-
A
bytesis one counted allocation, headered like a Str. ADR 0025's header (count, length, an unused code-point count) sits before the data. The value is one machine word pointing at the data. Binary data contains NUL by definition, so a string of bytes that ends at the first zero byte is not a byte string; the length is stored and each operation reads it from the header. The type is incomplete outside the bytes runtime: no code outside it dereferences abytes. -
A literal is its blob. Each backend emits a bytes literal as it emits a Str literal object, immortal by the header and holding the length, so evaluating a literal allocates nothing.
b""is one immortal empty object. -
Counted as a Str is (0026): a frame owns what an owning helper hands over, a function returning
byteshands over a reference, and a rebinding releases the old value. Abyteshas counters of its own and a per-task leak report, so each report says what the type left. It is copied where it crosses:pygo.net's receive builds abytesholding a copy and frees its buffer. A task argument is copied by the spawner and released by the body, as a Str is (A64), since counts are not atomic. -
The operations are CPython's.
lencounts bytes, where Str's counts code points; the difference is the point of the type. Comparison ismemcmpover the common prefix, then by length, which is CPython's ordering onbytesand whatstrcmpcannot give once NUL is a legal element. Truthiness is non-emptiness.b[i]is one bounds-checked byte load, anint, raisingIndexError. A slice follows CPython's slice adjustment.a + b,b * nandn * b(empty forn <= 0) andsep.join(xs)over a list, a generator or a tuple ofbyteseach make a new countedbytes;joinis one lowering withstr.join.bytes(xs)of a list of ints makes one byte per int and raises CPython'sValueError("bytes must be in range(0, 256)")before anything else is read.encodeanddecodeare 0043's.
b"..." % args with a literal format is lowered piece by piece, every argument evaluated once and first. A literal piece is the bytes themselves. A numeric conversion (d, i, x, f and the rest, with a width, a precision and the - and 0 flags) is the Str conversion's ASCII text encoded. %c of an int is that byte, with CPython's OverflowError outside range(256). A bytes under %s or %b gives its bytes, and %% gives %. The pieces are joined as bytes. Joining them as a Str and encoding the result would be wrong for a literal byte or a %c above 0x7f, which UTF-8 spells in two bytes. Other conversions are refused by name.
The text of a bytes is CPython's repr: b'...', or b"..." when the data holds a ' and no "; the backslash, the quote, tab, newline and return escaped; any other byte below 0x20 or from 0x7f up as \xhh. It is what print, str, repr and an f-string give, what the printing of a container or union holding a bytes shows, and the text of a missing bytes key's KeyError.
int.to_bytes and int.from_bytes lower with byteorder the literal "big" or "little" and signed a literal bool, raising CPython's errors with their messages: a negative length is a ValueError, a negative int unsigned and an int that does not fit are OverflowErrors. A length past eight bytes fills with the sign, as an arbitrary-width int does. Where int grows (0075), a to_bytes of a value past 64 bits gives CPython's bytes, a length past 64 bits raises CPython's OverflowError, and a from_bytes of any length is CPython's value. With the 64-bit int, a value that needs more than 64 bits is the integer overflow every 64-bit int operation is (0002): a debug build stops naming it, a release build keeps the low 64 bits. from_bytes takes a bytes; CPython also takes any iterable of ints, which stays refused.
sum, min and max of a list[bytes] are refused by name (CPython's sum of bytes is a TypeError).
-
A
bytesis held wherever a Str is: a field, a list element, a dict key or value and a set member, a union case (0029), andbytes | None, whose payload pointer is null forNone(0066's thin family). Each container releases it with itself;copy.deepcopyshares it as the immutable value it is. -
A
bytearraylocal, and nothing more ofbytearray. Shed Skin's sokoban copies a board withbytearray(data), writes into the copy, and returnsbytes(data2). A name bound in a function only byname = bytearray(...)(of abytes, of an int, or of nothing) holds a newbytesthat only that name holds.ba[i] = vchecks the value, raising CPython'sValueError("byte must be in range(0, 256)"), then the index, raisingIndexError("bytearray index out of range"), in CPython's order, and writes in place.ba[i]andlen(ba)read it, andbytes(ba)copies it out, so a later write cannot reach the copy. Any other read of the name is refused before the function is lowered, since it could share the buffer: a shared buffer written in place would need a mutable type this compiler does not have. -
bytesis a value, unlike a handle, and saying so cost more than adding a row. The test for an opaque value was "not numeric and not Str", stated over kinds so that the next type is refused by default. It is now "not numeric and not in a named set of non-numeric value types". The set is keyed by identity because postyp givesStrandBytesthe same kind,'s'. A kind test would have admittedBytesfrom the day it was declared, which is the accept-then-wrong shape.
The same collision is why three permissive fallbacks had to be closed by hand; each was so ordinary that all backends would have compiled it in agreement. promote(Bytes, Bytes) is Bytes, so b1 + b2 emitted arithmetic on two pointers; truth's fallthrough is != 0, which on a pointer is True for any value a bytes can hold; and bytes resolves in an annotation position, so bytes(x) and str(b) both reached the cast machinery. Each now has its own lowering or diagnostic. The verifier also gained IR16 (ADR 0014) so that no non-numeric operand can reach arithmetic by a route the frontend misses.
-
A
bytesmay cross a task boundary; it was the first val added to pygo's sendable set since the set was created. It qualifies for the same reason Str does: a Pythonbytesis immutable, socopy.deepcopyreturns the same object interpreted, and passing a copy compiled is indistinguishable, so pygo D15's copy-on-send invariant holds.Chan[bytes]is not lowered: a channel moves an element bymemcpyof a fixed size, and abytespayload sits behind a pointer, the same aggregate-element question asChan[list[int]](A13). -
A distinct C type in the ABI vocabulary. The C type of a
bytesmaps toBytes, distinct fromconst char *. Two types that share a kind and a machine width are the pair an ABI check must be able to tell apart; one row for both would make them interchangeable at each runtime-helper boundary, the classIR13exists to catch. A handle is opaque to this compiler, so no C type can name it (void *);bytesis a value whose layout the runtime owns, so it can. -
A
bytesstops at the stable C ABI. An exported signature taking or returning one is refused (PP501). The C type in a generated header is incomplete, with a runtime helper as the only constructor, so a C caller could hold one and not make one. Such a caller wants(const char *, int64_t); choosing that is an ABI decision (spec §9.1, upstream U13).Strexports because a NUL-terminatedconst char *is a type C already has. A private helper takingbytescompiles into an extension module unchanged.
Consequences¶
bytesvalues compile on all three backends and are byte-identical to CPython, interior NUL included, a case ADR 0004's original Str representation rejected outright.pygo.netis expressible (ADR 0016), and so are binary files (0061).- Opening the type opened all annotation positions at once, so the narrowness of what a
bytescan do is enforced at each operation. - A program that holds a
byteslinks the Str unit (its repr is a Str), and one that links the list or object runtime links the bytes unit. - The first descriptor representation was A3's length-prefixed Str prototyped: it showed the gains (interior NUL,
chr(0), an O(1)len) and the cost of the literal path. The Str migration of 0025 took the header instead of the descriptor, which closed A3, and A174 broughtbytesonto the same header.