The Canon / lab 1

What is in the bytes

The real memory contents of eight objects, taken with ctypes.string_at(id(obj), sizeof) and broken down into fields.

CPython 3.11.15Linux x86-64real bytes, not drawn ones

A mechanism described in words and a mechanism you have turned over in your hands settle differently. Below is not an illustration but a dump: every byte was taken from a live process, every field checked against a known value (the count, the length, the hash, the type pointer). Hover over a field in the table or tap it, and the corresponding bytes light up.

1How to reproduce it

Everything shown here is captured with five lines. Paste them into a terminal or a notebook as they are:

import ctypes, sys, struct

obj = 2**70
n = sys.getsizeof(obj)
raw = ctypes.string_at(id(obj), n)
print(n, raw.hex(' '))
print("refcnt:", struct.unpack_from("<q", raw, 0)[0])
print("type is int:", struct.unpack_from("<Q", raw, 8)[0] == id(int))
print("ob_size:", struct.unpack_from("<q", raw, 16)[0])
print("digits:", [struct.unpack_from("<I", raw, 24 + 4*i)[0] for i in range(3)])

Careful: string_at reads raw memory at an address. A mistake in the length means a segfault of the whole process, not an exception. This is exactly the boundary beyond which Python stops being a safe language.

2What to take away

The numbers were obtained on CPython 3.11.15, Linux x86-64. On another version some of them will be different — and that is not a disclaimer but the content: object layout is a 🔧 implementation detail through and through. The wstr field of strings, which takes eight bytes here, was simply removed in 3.12.

Written by · The Python Canon