ZetCode

Python __bytes__ Method

Last modified November 17, 2026 Python 3.15

The built-in bytes() function can create a byte string from an integer, an iterable of integers, a text string with an encoding, or an object that defines __bytes__. This article focuses on the last form: how to implement __bytes__, how to design a stable binary layout, and how to decode the data back into an object. It also covers the return-type rules and the cases where bytes() does not use __bytes__ at all.

How bytes() builds a bytes object

The constructor has several forms. bytes(n) creates n zero bytes, bytes(iterable) converts integers in the range 0 to 255, and bytes(text, encoding) encodes a string. A bytes object passed to bytes() is copied.

bytes_forms.py
print(bytes(4))
print(bytes([65, 66, 67]))
print(bytes("héllo", "utf-8"))
print(bytes(b"raw"))

The first line contains four zero bytes, not the decimal representation of the number four. The second line converts the integers 65, 66, and 67 to ABC. The text form requires an explicit encoding, and the last line copies an existing bytes object.

$ python bytes_forms.py
b'\x00\x00\x00\x00'
b'ABC'
b'h\xc3\xa9llo'
b'raw'

A basic __bytes__ method

bytes(obj) calls obj.__bytes__() when the method exists. The method takes only self and must return a bytes object. The following Point class stores two coordinates in one byte each and provides a class method for the reverse operation.

point_bytes.py
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __bytes__(self):
        return bytes([self.x, self.y])

    @classmethod
    def from_bytes(cls, data):
        x, y = data
        return cls(x, y)


point = Point(3, 4)
data = bytes(point)

print(data)
print(data.hex())
print(len(data))
print(Point.from_bytes(data).__dict__)

bytes(point) produces b'\x03\x04', and hex() shows the two bytes as 0304. Point.from_bytes unpacks the same two bytes and creates a new instance. The __bytes__ method defines only the encoding; a decoder must be written separately, because Python has no generic bytes.fromobj().

$ python point_bytes.py
b'\x03\x04'
0304
2
{'x': 3, 'y': 4}

Values must fit in a byte

Each element passed to bytes() must be between 0 and 255. A coordinate of 300 or -1 raises ValueError before any bytes are created. The method should validate its fields or use a wider integer format when the domain needs a larger range.

point_errors.py
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __bytes__(self):
        return bytes([self.x, self.y])


try:
    print(bytes(Point(300, 4)))
except ValueError as e:
    print(type(e).__name__, e)

try:
    print(bytes(Point(-1, 4)))
except ValueError as e:
    print(type(e).__name__, e)

Both calls fail with bytes must be in range(0, 256). A binary format should state its ranges explicitly and either raise a clear error or choose a format that can represent the values, such as a four-byte integer.

$ python point_errors.py
ValueError bytes must be in range(0, 256)
ValueError bytes must be in range(0, 256)

Packing structured records

The struct module is the standard way to build fixed binary layouts. The following Person record stores the UTF-8 name length, the name bytes, an unsigned integer age, and a float height. The format string uses < for little-endian order and no native padding.

person_struct.py
import struct


class Person:
    def __init__(self, name, age, height):
        self.name = name
        self.age = age
        self.height = height

    def __bytes__(self):
        name = self.name.encode("utf-8")
        return struct.pack(f"<I{len(name)}sIf", len(name), name, self.age, self.height)

    @classmethod
    def from_bytes(cls, data):
        name_len = struct.unpack_from("<I", data)[0]
        name, age, height = struct.unpack_from(f"<{name_len}sIf", data, 4)
        return cls(name.decode("utf-8"), age, height)


person = Person("Alice", 30, 1.75)
data = bytes(person)
print(len(data))
print(data.hex())
print(struct.unpack(f"<I5sIf", data))
print(Person.from_bytes(data).__dict__)

The encoded record is 17 bytes: four for the length, five for Alice, four for the age, and four for the height. The format string <I5sIf has no alignment gaps. Without the leading <, native alignment could insert padding and the decoder would have to use exactly the same platform-dependent layout. The length prefix tells the decoder how many name bytes to read.

$ python person_struct.py
17
05000000416c6963651e0000000000e03f
(5, b'Alice', 30, 1.75)
{'name': 'Alice', 'age': 30, 'height': 1.75}

A network packet

A binary protocol often needs a fixed header followed by a variable payload. This packet stores one type byte, a two-byte sequence number, and a one-byte payload length. The methods validate the ranges before packing, and from_bytes checks that the length prefix matches the actual payload.

packet.py
class Packet:
    def __init__(self, kind, sequence, payload):
        if not 0 <= kind <= 255:
            raise ValueError("kind must fit in one byte")
        if not 0 <= sequence <= 65535:
            raise ValueError("sequence must fit in two bytes")
        if len(payload) > 255:
            raise ValueError("payload must fit in one byte length")
        self.kind = kind
        self.sequence = sequence
        self.payload = payload

    def __bytes__(self):
        header = bytes([
            self.kind,
            self.sequence >> 8,
            self.sequence & 0xFF,
            len(self.payload),
        ])
        return header + self.payload

    @classmethod
    def from_bytes(cls, data):
        kind, high, low, length = data[:4]
        payload = data[4:]
        if len(payload) != length:
            raise ValueError("length prefix does not match payload")
        return cls(kind, (high << 8) | low, payload)


packet = Packet(1, 256, b"Hello")
data = bytes(packet)

print(data)
print(data.hex())
print(Packet.from_bytes(data).__dict__)

The header 01 01 00 05 means type 1, sequence 256, and a five-byte payload. The payload follows as Hello in ASCII. The decoder reconstructs the same object from the bytes, so the format can be sent over a socket and parsed by a peer that knows the layout.

$ python packet.py
b'\x01\x01\x00\x05Hello'
0101000548656c6c6f
{'kind': 1, 'sequence': 256, 'payload': b'Hello'}

Writing a valid BMP file

A complete binary file format is a good test of __bytes__. The following class builds a 24-bit BMP image with a 54-byte header and a block of pixel rows. Each row is padded to a multiple of four bytes, as the BMP format requires.

bmp_image.py
import struct


class BMPImage:
    def __init__(self, width, height, color=(0, 0, 255)):
        self.width = width
        self.height = height
        self.color = color

    def __bytes__(self):
        row = bytes(self.color) * self.width
        row += b"\x00" * ((4 - len(row) % 4) % 4)
        pixels = row * self.height
        header = struct.pack("<2sIHHI", b"BM", 54 + len(pixels), 0, 0, 54)
        dib = struct.pack(
            "<IiiHHIIiiII", 40, self.width, self.height, 1, 24, 0,
            len(pixels), 2835, 2835, 0, 0
        )
        return header + dib + pixels


image = BMPImage(3, 2)
data = bytes(image)
print(len(data))
print(data[:14].hex())

with open("image.bmp", "wb") as f:
    f.write(data)

The file is 78 bytes: a 54-byte header plus two rows of 12 bytes each for a 3-pixel-wide, 24-bit image. The file command reads the header and identifies the result as a Windows 3.x bitmap. Writing only the header, as the old version of this example did, would leave a truncated file with no pixel data.

$ python bmp_image.py
78
424d4e0000000000000036000000
$ file image.bmp
image.bmp: PC bitmap, Windows 3.x format, 3 x 2 x 24, image size 24, resolution 2835 x 2835 px/m, cbSize 78, bits offset 54

Return types and fallbacks

__bytes__ must return an actual bytes object. Returning a string or a bytearray raises TypeError. The bytearray() constructor does not call __bytes__ at all, even when the method exists, so an object that should work with both constructors needs an explicit conversion or a bytes-like protocol.

type_rules.py
class TextBytes:
    def __bytes__(self):
        return "text"


class ByteArrayBytes:
    def __bytes__(self):
        return bytearray(b"abc")


class GoodBytes:
    def __bytes__(self):
        return b"abc"


class IndexOnly:
    def __index__(self):
        return 3


for obj in (TextBytes(), ByteArrayBytes()):
    try:
        print(bytes(obj))
    except TypeError as e:
        print(type(e).__name__, e)

print(bytes(GoodBytes()))

try:
    print(bytearray(GoodBytes()))
except TypeError as e:
    print(type(e).__name__, e)

print(bytes(IndexOnly()))
print(bytes(bytearray(b"abc")))

TextBytes and ByteArrayBytes fail with clear messages from bytes(). GoodBytes works with bytes() but not with bytearray(). An object with only __index__ produces a zero-filled bytes object of that length, and bytes(bytearray(b"abc")) copies the mutable buffer. These fallbacks are easy to confuse with a binary representation, so implement __bytes__ when the conversion should have a specific meaning.

$ python type_rules.py
TypeError TextBytes.__bytes__() must return a bytes, not str
TypeError ByteArrayBytes.__bytes__() must return a bytes, not bytearray
b'abc'
TypeError cannot convert 'GoodBytes' object to bytearray
b'\x00\x00\x00'
b'abc'

Best practices

A binary representation is a contract with every reader and writer of the data, so document it carefully:

Source

object.__bytes__ - Python documentation

bytes - Python documentation

struct - Python documentation

bytes() - Python documentation

In this article we have implemented the __bytes__ method. We have covered the bytes constructor, simple and structured binary layouts, network packets, a valid BMP file, and the rules for return types and fallbacks. For related topics, see Python bytes type, Python bytes built-in, Python bytearray built-in, Python encode decode, and Python __str__ method.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.