The bytes() built-in function constructs an immutable sequence of integers in the range 0 ≤ x ≤ 255.
Binary Data & Wire Protocols: bytes objects represent raw machine-level memory buffers, file streams, and network packets. String inputs require an explicit encoding parameter, while integer counts allocate zero-filled buffers. For an editable in-place byte buffer, use companion constructor bytearray(). To convert binary data back to text or hexadecimal strings, see str() and hex().
The bytes() constructor supports four distinct initialization patterns:
# Formal syntax of built-in bytes()
# Form 1: Zero-argument constructor
empty_bytes = bytes()
# Form 2: Integer count (creates zero-filled byte array)
zero_buffer = bytes(count)
# Form 3: String conversion with encoding and error policies
encoded_bytes = bytes(string, encoding='utf-8', errors='strict')
# Form 4: Iterable of integers (0 <= x <= 255)
seq_bytes = bytes(iterable_of_ints)
| Parameter | Type Accepted | Behavioral Details |
|---|---|---|
source |
int, str, Iterable[int], buffer |
Integer allocates zero-filled bytes; string requires encoding; iterable requires integers 0–255. |
encoding |
str (optional) |
Encoding standard (e.g. 'utf-8', 'ascii'). Mandatory when source is a string. |
errors |
str (optional) |
Error handling scheme: 'strict', 'ignore', 'replace'. |
| Return Value | bytes object |
An immutable sequence of single bytes. |
Passing an integer preallocates a buffer of null bytes (