Every Value Is a Pointer to a Struct

Contents
On a freshly installed Ubuntu 18.04, the Python integer 1000 is 28 bytes of memory at an address
you can print. The first eight bytes count how many things refer to it. The next eight are the
address of a C structure that describes what an integer is. Eight more say how many 30-bit digits
follow, and the last four hold the number itself, as the bytes e8 03 00 00. Python goes to some
lengths so that you never have to know any of this. It does not always succeed, and the places
where it fails are the subject of this series.
Python the language is a specification of what programs mean. Python as most people run it is a C program called CPython, a 4.5 MB executable on this system. Every value your program touches is a C struct that program allocated, and every operation is a C function it calls. This post starts at the bottom: what a value is in memory. I read raw bytes out of live objects, print the same fields from a C program that embeds the interpreter, and then look at four places where the C underneath leaks through into ordinary Python code.
This is Part 1 of a series on the CPython runtime: the interpreter, its memory, its threads and its
relationship with C, rather than the language it runs. It is written for Python programmers who have
written a little C (pointers, structs, malloc) but have never opened CPython’s source. Everything
here ran on Ubuntu 18.04 as it shipped in April: python3 3.6.5-3 and gcc 7.3.0 from the release
archive. The output is pasted from those runs, and the note at the end says exactly where and how.
The interpreter is a C program
Start with the file you run:
$ ls -l /usr/bin/python3 /usr/bin/python3.6
lrwxrwxrwx 1 root root 9 Apr 10 2018 /usr/bin/python3 -> python3.6
-rwxr-xr-x 2 root root 4576440 Apr 1 2018 /usr/bin/python3.6
$ readelf -h /usr/bin/python3.6 | grep Type
Type: EXEC (Executable file)
That is 4,576,440 bytes of compiled C. Debian and Ubuntu link the interpreter’s core, the library
called libpython, straight into this executable. It contains the parser, the compiler that turns
source into bytecode, the loop that runs the bytecode, the memory allocator, and the built-in types:
int, float, str, tuple, list, dict and the rest. Each built-in type is written in C, as
a file of functions plus one statically allocated struct that describes the type.
The descriptions of those types are ordinary global variables, and you can find them. id() in
CPython returns an object’s address, a fact we’ll come back to, so the address of the type int
is one function call away. The binary exports its C symbols so that extension modules can link
against them, which means gdb can name what lives at an address even in this stripped,
release-build interpreter:
$ python3 -c 'print(hex(id(int))); print(hex(id(float))); print(hex(id(None)))'
0x9db840
0x9d82e0
0x9dfba0
$ gdb -batch -ex 'info symbol 0x9db840' /usr/bin/python3.6
PyLong_Type in section .data of /usr/bin/python3.6
$ gdb -batch -ex 'info symbol 0x9d82e0' /usr/bin/python3.6
PyFloat_Type in section .data of /usr/bin/python3.6
$ gdb -batch -ex 'info symbol 0x9dfba0' /usr/bin/python3.6
_Py_NoneStruct in section .data of /usr/bin/python3.6
The class int is the C variable PyLong_Type. (Python 2 had two integer types, int and
long. Python 3 kept only the arbitrary-precision one and named it int, but in C it is still
“long”, so the C functions all start with PyLong_.) float is PyFloat_Type, and None is a
struct called _Py_NoneStruct. None of these are Python objects that wrap something in C. They
are the C variables, sitting in the .data section of the executable.
Those three addresses are short and low, and they are the same every time you start Python on this
system. readelf said EXEC: Ubuntu builds this executable without position independence, so it
loads at the same address in every process and its global variables never move. Objects created at
run time live on the heap, which the kernel places at a random address in every process. Every
other address in this post is therefore different on every run, while these three are not.
Two fields every object starts with
Every Python object, of every type, begins with the same two fields. This is the definition from
Include/object.h in the 3.6.5 source:
typedef struct _object {
_PyObject_HEAD_EXTRA
Py_ssize_t ob_refcnt;
struct _typeobject *ob_type;
} PyObject;
typedef struct {
PyObject ob_base;
Py_ssize_t ob_size; /* Number of items in variable part */
} PyVarObject;
#define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt)
#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
#define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size)
_PyObject_HEAD_EXTRA expands to nothing in a normal build. A special debug build adds two
pointers there, so that it can keep every live object on one linked list. Without it, a PyObject
is 16 bytes on a 64-bit machine:
ob_refcntis the reference count: how many pointers to this object exist in the running program.Py_ssize_tis a signed integer as wide as a pointer, eight bytes here.ob_typeis a pointer to the type object, the struct that says what this object is and holds the C functions that implement its behaviour. For anintit points atPyLong_Type.
Objects whose length varies with their contents, such as integers, tuples and strings, start with
a PyVarObject instead. That is the same 16 bytes plus ob_size, a count of items, for 24 in all.
Everything else in CPython is built on these two fields. The interpreter handles every value as
a PyObject *, a pointer to this header, whatever the value really is. To do anything with an
object, it follows ob_type and calls a function pointer it finds there. Adding two objects means
finding the type’s addition function. Printing one means finding the type’s repr function.
Hashing one means calling its tp_hash. A Python variable is not a box that holds a value. It is a
name bound to one of these pointers.
Taking 1000 apart
Python can read raw memory. The standard library’s ctypes module exists to call C libraries, and
one of its helpers, ctypes.string_at(address, size), returns size bytes starting at any address
as a bytes object. Combine it with id() and sys.getsizeof() and you can look at an object’s
memory from inside the program that owns it. Reading is safe as long as the object stays alive
while you read and you don’t read past its end. Writing is another matter, and we’ll get to it.
import ctypes, struct, sys
x = int("1000") # made at run time, so it is a brand-new object
size = sys.getsizeof(x)
mem = ctypes.string_at(id(x), size)
print("id(x) =", hex(id(x)))
print("getsizeof(x) =", size)
print("raw bytes =", mem.hex())
refcnt, typ, ob_size = struct.unpack_from("<qQq", mem, 0)
digit, = struct.unpack_from("<I", mem, 24)
print("ob_refcnt =", refcnt)
print("ob_type =", hex(typ), " id(int) =", hex(id(int)))
print("ob_size =", ob_size)
print("ob_digit[0] =", digit)
$ python3 peek.py
id(x) = 0x7a696ee87ef0
getsizeof(x) = 28
raw bytes = 010000000000000040b89d00000000000100000000000000e8030000
ob_refcnt = 1
ob_type = 0x9db840 id(int) = 0x9db840
ob_size = 1
ob_digit[0] = 1000
I wrote int("1000") instead of the literal 1000 on purpose. A literal is a constant, and the
compiler stores constants in the code object, which then holds a reference of its own. Parsing a
string makes a new object that nothing else knows about.
The raw bytes are the whole object. Split them into the fields of the struct, and remember that x86 is little-endian, so the lowest byte of each number comes first:
| Offset | Bytes | Field | Value |
|---|---|---|---|
| 0 | 01 00 00 00 00 00 00 00 | ob_refcnt | 1 |
| 8 | 40 b8 9d 00 00 00 00 00 | ob_type | 0x9db840, PyLong_Type |
| 16 | 01 00 00 00 00 00 00 00 | ob_size | 1 digit |
| 24 | e8 03 00 00 | ob_digit[0] | 0x3e8 = 1000 |
The reference count is 1, because exactly one thing refers to this object: the module-level name
x. The type pointer is the address of PyLong_Type, the same 0x9db840 as before. ob_size says
the number has one digit, and the digit is 1000. Those 28 bytes are everything CPython stores for
this integer. There is no hidden extra size field, no flags word and no cached hash.
The struct format strings name the C types. < means little-endian with no padding, q is a
signed 64-bit integer, Q an unsigned one, and I an unsigned 32-bit integer. They decode the same
bytes that C code reads through the struct definition.
The same object, seen from C
To check that I’m not fooling myself, here is a small C program that starts the interpreter, makes
the integer 1000 with PyLong_FromLong, and prints its fields through CPython’s own struct
definitions. This is what “embedding Python” means: libpython is a C library, and any C program
can call it.
#include <Python.h>
#include <longintrepr.h> /* the full definition of struct _longobject */
#include <stddef.h> /* offsetof */
#include <stdio.h>
int main(void)
{
Py_Initialize();
PyObject *x = PyLong_FromLong(1000); /* a new int object holding 1000 */
PyLongObject *lx = (PyLongObject *)x;
printf("address %p\n", (void *)x);
printf("ob_refcnt %zd\n", x->ob_refcnt);
printf("ob_type %p (&PyLong_Type = %p, tp_name \"%s\")\n",
(void *)x->ob_type, (void *)&PyLong_Type, x->ob_type->tp_name);
printf("ob_size %zd\n", Py_SIZE(x));
printf("ob_digit[0] %u\n", lx->ob_digit[0]);
printf("sizeof(PyObject) %zu, sizeof(PyVarObject) %zu, offsetof ob_digit %zu\n",
sizeof(PyObject), sizeof(PyVarObject), offsetof(PyLongObject, ob_digit));
PyObject *one = PyLong_FromLong(1), *again = PyLong_FromLong(1);
printf("PyLong_FromLong(1) twice: %p %p\n", (void *)one, (void *)again);
Py_DECREF(again);
Py_DECREF(one);
Py_DECREF(x);
Py_Finalize();
return 0;
}
$ gcc -o embed embed.c $(python3-config --cflags) $(python3-config --ldflags) -no-pie
$ ./embed
address 0x7ababfd97fd0
ob_refcnt 1
ob_type 0x601060 (&PyLong_Type = 0x601060, tp_name "int")
ob_size 1
ob_digit[0] 1000
sizeof(PyObject) 16, sizeof(PyVarObject) 24, offsetof ob_digit 24
PyLong_FromLong(1) twice: 0x7ababfa93c00 0x7ababfa93c00
The fields agree, and so do the sizes: a 16-byte PyObject, a 24-byte PyVarObject, and digits
starting at offset 24. PyLong_Type sits at a different address here, 0x601060, because this
program has its own copy of libpython linked in. The tp_name field of the type struct holds the
string "int", which is what type(x).__name__ returns. The last line is a preview: asking C for
the integer 1 twice gives back the same address both times. That is the first leak, and we’ll
come to it.
The -no-pie flag is a quirk of 18.04. python3-config --cflags asks gcc to compile without
position independence, to match the interpreter, but --ldflags doesn’t ask the linker for the
same. 18.04’s gcc builds position-independent executables by default, so without the flag the link
fails with relocation R_X86_64_32 against '.rodata.str1.1' can not be used when making a PIE object.
Py_DECREF at the end is how C code says it has finished with an object, and a later section is
about it. Every C function that hands out a new reference, as PyLong_FromLong does, makes
its caller responsible for exactly one Py_DECREF.
Integers are arrays of digits
Python integers have no maximum. 2**64 is as legal as 2**6, and 10**100 works without
complaint. A C long is 64 bits on this machine, and something has to hold the rest. This is the
struct, with the comment that explains it, from Include/longintrepr.h:
/* Long integer representation.
The absolute value of a number is equal to
SUM(for i=0 through abs(ob_size)-1) ob_digit[i] * 2**(SHIFT*i)
Negative numbers are represented with ob_size < 0;
zero is represented by ob_size == 0.
...
CAUTION: Generic code manipulating subtypes of PyVarObject has to
aware that ints abuse ob_size's sign bit.
*/
struct _longobject {
PyObject_VAR_HEAD
digit ob_digit[1];
};
An integer is a sign plus a list of digits in base 230, least significant first. Each
digit is a 32-bit unsigned integer, of which 30 bits are used. ob_size holds the number of
digits, and its sign is the sign of the number: CPython stores −1000 as ob_size = -1 with digit
1000. The array is declared with length 1, the old C idiom for “a variable number of these, allocated
together with the header”. The allocation function allocates the header plus as many digits as the
number needs, in one block.
Here are some integers taken apart, with a check that recomposes each one from its digits:
import ctypes, struct, sys
def digits(n):
"""Return (ob_size, [ob_digit...]) read from the int object's own memory."""
mem = ctypes.string_at(id(n), sys.getsizeof(n))
ob_size, = struct.unpack_from("<q", mem, 16)
count = max(abs(ob_size), 1) if len(mem) > 24 else 0
return ob_size, list(struct.unpack_from("<%dI" % count, mem, 24))
print(sys.int_info)
print()
print("%-22s %9s %7s %s" % ("value", "getsizeof", "ob_size", "ob_digit"))
for text in ["0", "1", "1073741823", "1073741824", "-1073741824",
"18446744073709551616", "10**100"]:
n = eval(text) if "**" in text else int(text)
size, ds = digits(n)
print("%-22s %9d %7d %s" % (text, sys.getsizeof(n), size, ds))
sign = -1 if size < 0 else 1
assert n == sign * sum(d << (30 * i) for i, d in enumerate(ds))
$ python3 digits.py
sys.int_info(bits_per_digit=30, sizeof_digit=4)
value getsizeof ob_size ob_digit
0 24 0 []
1 28 1 [1]
1073741823 28 1 [1073741823]
1073741824 32 2 [0, 1]
-1073741824 32 -2 [0, 1]
18446744073709551616 36 3 [0, 0, 16]
10**100 72 12 [0, 0, 0, 195281920, 843253928, 74052266, 753141986, 864222434, 187139268, 319681452, 614126169, 4]
Every row follows from the comment in the header file:
- Zero has no digits at all, so it is 24 bytes: just the
PyVarObjectheader. - 230 − 1 = 1,073,741,823 is the largest number that fits in one digit. One more and
the number needs a second digit: 230 is
[0, 1], meaning 0 + 1 × 230. The object grows by four bytes at exactly that point. - −230 has the same digits as 230, with
ob_size−2. - 264 needs three digits. Two digits hold 60 bits, and 264 is 16 × 260, so the top digit is 16.
- 10100 is a googol: 333 bits, so 12 digits and 72 bytes. Its three low digits are zero because 10100 = 2100 × 5100 is divisible by 290.
The assert passed on every row, so the formula in the comment is the whole truth. An integer’s
size is 24 + 4 × ⌈bits / 30⌉ bytes, except zero, which is 24.
This is also why sys.getsizeof(1) is 28 bytes when a C long is 8. The value takes four bytes and
the header takes 24. For an integer, the bookkeeping is six times the size of the data.
A float is a C double with a header
Floats are simpler, because a C double already does everything a Python float does:
typedef struct {
PyObject_HEAD
double ob_fval;
} PyFloatObject;
It has no ob_size, because every float is the same size: 16 bytes of header and 8 bytes of
IEEE 754 double. Here are the bytes of 0.1:
import ctypes, struct, sys
f = float("0.1")
mem = ctypes.string_at(id(f), sys.getsizeof(f))
print("getsizeof(f) =", sys.getsizeof(f))
print("bytes 16..24 of f =", mem[16:24].hex())
print("struct.pack('<d',.1) =", struct.pack("<d", 0.1).hex())
print("f.hex() =", f.hex())
from decimal import Decimal
print("what is stored =", Decimal(f))
$ python3 floats.py
getsizeof(f) = 24
bytes 16..24 of f = 9a9999999999b93f
struct.pack('<d',.1) = 9a9999999999b93f
f.hex() = 0x1.999999999999ap-4
what is stored = 0.1000000000000000055511151231257827021181583404541015625
The eight bytes after the header are exactly the bytes a C program would store for double d = 0.1;. Read as a little-endian 64-bit number, that is 0x3fb999999999999a: a sign bit of 0, an
exponent field of 0x3fb (which encodes 2−4), and a fraction field of
0x999999999999a, the binary expansion of 0.6 cut off and rounded up. float.hex() prints the
same value in a form a person can read.
Python does not hide anything here. It calls the C library for parsing, printing, math.sin and
the rest, and it does arithmetic with the processor’s own floating-point instructions. Every surprise
a C programmer knows about doubles is a Python surprise too, including the fact that what’s stored
for 0.1 is a little more than 0.1. The last line shows it exactly: a Decimal built from a float
converts its binary value exactly, with no rounding.
There is one CPython detail worth knowing now. Programs create and destroy floats constantly, so
floatobject.c keeps up to 100 freed float objects on a private list (PyFloat_MAXFREELIST) and
reuses them before asking the allocator for memory. A float that dies is often reborn, at the same
address, as the next float you make.
Containers hold addresses
A tuple of two numbers does not contain two numbers. It contains two pointers:
typedef struct {
PyObject_VAR_HEAD
PyObject *ob_item[1];
/* ob_item contains space for 'ob_size' elements. ... */
} PyTupleObject;
A list holds a pointer to a separate array of pointers, because a list can grow, and growing
means realloc, which may move the array:
typedef struct {
PyObject_VAR_HEAD
/* Vector of pointers to list elements. list[0] is ob_item[0], etc. */
PyObject **ob_item;
/* ob_item contains space for 'allocated' elements. The number
* currently in use is ob_size.
...
*/
Py_ssize_t allocated;
} PyListObject;
Both are easy to check. The helper word(addr, k) reads the k-th eight-byte word at an address:
import ctypes, gc, struct, sys
def word(addr, k=0):
return struct.unpack("<q", ctypes.string_at(addr + 8 * k, 8))[0]
a, b = int("1000"), float("1.5")
t = (a, b)
print("tuple: getsizeof =", sys.getsizeof(t))
print(" ob_size =", word(id(t), 2))
print(" ob_item[0] =", hex(word(id(t), 3)), " id(a) =", hex(id(a)))
print(" ob_item[1] =", hex(word(id(t), 4)), " id(b) =", hex(id(b)))
l = [a, b]
print("list: getsizeof =", sys.getsizeof(l))
print(" ob_size =", word(id(l), 2), " allocated =", word(id(l), 4))
items = word(id(l), 3)
print(" ob_item =", hex(items), "-> [", hex(word(items, 0)), ",", hex(word(items, 1)), "]")
l.append(a)
print("after append: ob_size =", word(id(l), 2), " allocated =", word(id(l), 4),
" ob_item =", hex(word(id(l), 3)), " getsizeof =", sys.getsizeof(l))
# The 24 bytes *before* id(l) belong to the cycle collector.
print("gc header of l:", ctypes.string_at(id(l) - 24, 24).hex())
nxt = word(id(l) - 24, 0)
owner = [o for o in gc.get_objects() if id(o) - 24 == nxt]
print(" gc_next points at the header of:", type(owner[0]).__name__ if owner else "a gc list head")
print(" gc.is_tracked(l) =", gc.is_tracked(l), " gc.is_tracked(a) =", gc.is_tracked(a))
$ python3 containers.py
tuple: getsizeof = 64
ob_size = 2
ob_item[0] = 0x7dff79d13b50 id(a) = 0x7dff79d13b50
ob_item[1] = 0x7dff79dd1078 id(b) = 0x7dff79dd1078
list: getsizeof = 80
ob_size = 2 allocated = 2
ob_item = 0x7dff79dfb090 -> [ 0x7dff79d13b50 , 0x7dff79dd1078 ]
after append: ob_size = 3 allocated = 6 ob_item = 0x7dff79d33b70 getsizeof = 112
gc header of l: 500db42f000000007072c779ff7d0000faffffffffffffff
gc_next points at the header of: a gc list head
gc.is_tracked(l) = True gc.is_tracked(a) = False
The tuple’s two slots hold exactly the addresses id() reports for a and b. The list’s
ob_item points somewhere else entirely, and the two words there are the same two addresses. Put
a in a hundred containers and there is still one a, with a hundred pointers to it. This is what
“Python passes references” means in C: what gets copied is always the eight-byte address, never the
object.
The append shows the list’s growth policy. Appending a third element made CPython reallocate the
array with room for six, and the array moved: ob_item changed. The rule is in list_resize in
Objects/listobject.c:
/* This over-allocates proportional to the list size, making room
* for additional growth. The over-allocation is mild, but is
* enough to give linear-time amortized behavior over a long
* sequence of appends() in the presence of a poorly-performing
* system realloc().
* The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
*/
new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6);
For a new size of 3 that is 0 + 3 = 3 extra slots, and the function then adds the new size itself, which makes 6. A later append into a slot that is already allocated costs a store and an increment, with no allocation.
The moving array matters to C code. Any C code holding a pointer into a list’s array has to read
ob_item again after anything that might append, because the old array may have been freed. A
tuple’s items sit inside the tuple and never move.
What sys.getsizeof counts
Add up the list’s bytes: a 40-byte PyListObject plus a 16-byte array of two pointers is 56. Yet
sys.getsizeof says 80. After the append it is 112, which is 40 + 48 (six slots) + 24. The tuple
should be 24 + 2 × 8 = 40, and getsizeof says 64. The extra 24 bytes are in both, and they come
from _PySys_GetSizeOf in Python/sysmodule.c:
/* add gc_head size */
if (PyObject_IS_GC(o))
return ((size_t)size) + sizeof(PyGC_Head);
return (size_t)size;
Reference counting alone can never free two objects that point at each other, so CPython also has a
cycle collector, and it must be able to find every object that could be part of a cycle. Containers
(tuples, lists, dicts, instances of classes) carry a 24-byte header for it, placed before the
address that id() returns:
typedef union _gc_head {
struct {
union _gc_head *gc_next;
union _gc_head *gc_prev;
Py_ssize_t gc_refs;
} gc;
double dummy; /* force worst-case alignment */
} PyGC_Head;
#define _Py_AS_GC(o) ((PyGC_Head *)(o)-1)
So the memory allocated for the list starts 24 bytes before id(l), and the script read those
bytes. gc_next and gc_prev link the list into a doubly linked list of every tracked object of
its generation. gc_next pointed at no object at all, which makes sense: a newly tracked object is
added at the tail of the youngest generation’s list, so the next node after it is that list’s head,
a static PyGC_Head in the collector. The last word, fa ff ff ff ff ff ff ff, is −6. The
collector stores a state in gc_refs shifted left by one bit, to keep the lowest bit for a flag,
and −6 is _PyGC_REFS_REACHABLE, which is −3, shifted by one.
Integers and floats have no such header. They cannot point to other objects, so they can never be
part of a cycle, and gc.is_tracked(a) says so.
sys.getsizeof therefore counts the GC header, which lies before the object, and never counts
what the object points to. The list’s 112 bytes do not include a or b. The documentation says
both things (“Only the memory consumption directly attributed to the object is accounted for” and
“adds an additional garbage collector overhead”), but it is easy to read past them. Summing
getsizeof over a data structure measures its pointers, not its contents.
What CPython stores for each value
The bytes at id(obj), read from live objects, split into the fields of their C struct. Each square is one byte.
0 · int at 0xa6fa00 · sys.getsizeof 24 bytes
| offset | field | bytes | value |
|---|---|---|---|
| 0 | ob_refcnt | 41 02 00 00 00 00 00 00 | 577 |
| 8 | ob_type | 40 b8 9d 00 00 00 00 00 | 0x9db840 = int |
| 16 | ob_size | 00 00 00 00 00 00 00 00 | 0 |
1000 · int at 0x784ffcb64670 · sys.getsizeof 28 bytes
| offset | field | bytes | value |
|---|---|---|---|
| 0 | ob_refcnt | 01 00 00 00 00 00 00 00 | 1 |
| 8 | ob_type | 40 b8 9d 00 00 00 00 00 | 0x9db840 = int |
| 16 | ob_size | 01 00 00 00 00 00 00 00 | 1 |
| 24 | ob_digit[0] | e8 03 00 00 | 1000 |
-1000 · int at 0x784ffcc87fb0 · sys.getsizeof 28 bytes
| offset | field | bytes | value |
|---|---|---|---|
| 0 | ob_refcnt | 01 00 00 00 00 00 00 00 | 1 |
| 8 | ob_type | 40 b8 9d 00 00 00 00 00 | 0x9db840 = int |
| 16 | ob_size | ff ff ff ff ff ff ff ff | -1 |
| 24 | ob_digit[0] | e8 03 00 00 | 1000 |
2**30 · int at 0x784ffcc87fb0 · sys.getsizeof 32 bytes
| offset | field | bytes | value |
|---|---|---|---|
| 0 | ob_refcnt | 01 00 00 00 00 00 00 00 | 1 |
| 8 | ob_type | 40 b8 9d 00 00 00 00 00 | 0x9db840 = int |
| 16 | ob_size | 02 00 00 00 00 00 00 00 | 2 |
| 24 | ob_digit[0] | 00 00 00 00 | 0 |
| 28 | ob_digit[1] | 01 00 00 00 | 1 |
2**64 · int at 0x784ffcc3f828 · sys.getsizeof 36 bytes
| offset | field | bytes | value |
|---|---|---|---|
| 0 | ob_refcnt | 01 00 00 00 00 00 00 00 | 1 |
| 8 | ob_type | 40 b8 9d 00 00 00 00 00 | 0x9db840 = int |
| 16 | ob_size | 03 00 00 00 00 00 00 00 | 3 |
| 24 | ob_digit[0] | 00 00 00 00 | 0 |
| 28 | ob_digit[1] | 00 00 00 00 | 0 |
| 32 | ob_digit[2] | 10 00 00 00 | 16 |
0.1 · float at 0x784ffceef078 · sys.getsizeof 24 bytes
| offset | field | bytes | value |
|---|---|---|---|
| 0 | ob_refcnt | 01 00 00 00 00 00 00 00 | 1 |
| 8 | ob_type | e0 82 9d 00 00 00 00 00 | 0x9d82e0 = float |
| 16 | ob_fval | 9a 99 99 99 99 99 b9 3f | 0.1 |
(1000, 1.5) · tuple at 0x784ffcc72708 · sys.getsizeof 64 bytes
| offset | field | bytes | value |
|---|---|---|---|
| -24 | gc_next | 40 35 b0 fc 4f 78 00 00 | GC list link |
| -16 | gc_prev | a8 c6 b0 fc 4f 78 00 00 | GC list link |
| -8 | gc_refs | fa ff ff ff ff ff ff ff | −6: “reachable” (−3 << 1) |
| 0 | ob_refcnt | 01 00 00 00 00 00 00 00 | 1 |
| 8 | ob_type | 40 30 9e 00 00 00 00 00 | 0x9e3040 = tuple |
| 16 | ob_size | 02 00 00 00 00 00 00 00 | 2 |
| 24 | ob_item[0] | b0 7f c8 fc 4f 78 00 00 | 0x784ffcc87fb0 |
| 32 | ob_item[1] | 78 f0 ee fc 4f 78 00 00 | 0x784ffceef078 |
The pointers lead to: 0x784ffcc87fb0 → 1000; 0x784ffceef078 → 1.5;
[1000, 1.5] · list at 0x784ffcb00288 · sys.getsizeof 80 bytes
| offset | field | bytes | value |
|---|---|---|---|
| -24 | gc_next | 40 35 b0 fc 4f 78 00 00 | GC list link |
| -16 | gc_prev | e8 c8 b0 fc 4f 78 00 00 | GC list link |
| -8 | gc_refs | fa ff ff ff ff ff ff ff | −6: “reachable” (−3 << 1) |
| 0 | ob_refcnt | 01 00 00 00 00 00 00 00 | 1 |
| 8 | ob_type | e0 ad 9d 00 00 00 00 00 | 0x9dade0 = list |
| 16 | ob_size | 02 00 00 00 00 00 00 00 | 2 |
| 24 | ob_item | 00 91 f1 fc 4f 78 00 00 | 0x784ffcf19100 |
| 32 | allocated | 02 00 00 00 00 00 00 00 | 2 |
The pointers lead to: 0x784ffcc87fb0 → 1000; 0x784ffceef078 → 1.5; the list's own array, elsewhere on the heap, holds b07fc8fc4f78000078f0eefc4f780000: the same two addresses, little-endian.
Offsets are from id(obj). Negative offsets are the cycle collector's header, which only containers have and which sys.getsizeof counts. The type pointer is the same for every object of a type: int is 0x9db840, the C variable PyLong_Type. One run of Python 3.6.5; heap addresses differ on every run.
Counting references
The first field of every object is its reference count, and it changes every time a pointer to the object is stored or dropped. Here it is, read straight out of the object’s first eight bytes:
import ctypes, struct, sys
x = int("1000")
def refs():
# read ob_refcnt straight out of x's memory: the first 8 bytes
return struct.unpack("<q", ctypes.string_at(id(x), 8))[0]
print("fresh object: ", refs())
y = x
print("y = x: ", refs())
box = [x, x, x]
print("in a list 3 times:", refs())
d = {"k": x}
print("as a dict value: ", refs())
print("sys.getrefcount: ", sys.getrefcount(x), "(one more: its own argument)")
del box, d, y
print("after the dels: ", refs())
$ python3 refcnt.py
fresh object: 1
y = x: 2
in a list 3 times: 5
as a dict value: 6
sys.getrefcount: 7 (one more: its own argument)
after the dels: 1
Every binding and every slot is one count: the name x, the name y, three slots in the list and
one value in the dict make six. sys.getrefcount reports one more, because while it runs, its own
argument is a reference too. Its C implementation is one line,
return PyLong_FromSsize_t(arg->ob_refcnt);.
Each change is one of these two macros from Include/object.h, here without the debug-build
counters:
#define Py_INCREF(op) ( \
_Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \
((PyObject *)(op))->ob_refcnt++)
#define Py_DECREF(op) \
do { \
PyObject *_py_decref_tmp = (PyObject *)(op); \
if (_Py_DEC_REFTOTAL _Py_REF_DEBUG_COMMA \
--(_py_decref_tmp)->ob_refcnt != 0) \
_Py_CHECK_REFCNT(_py_decref_tmp) \
else \
_Py_Dealloc(_py_decref_tmp); \
} while (0)
An increment is a plain ob_refcnt++. A decrement subtracts one, and if the count reaches zero,
it calls _Py_Dealloc, which calls the type’s tp_dealloc function on the spot. There is no
deferred sweep and no separate thread: when the last reference goes, the object’s memory is
returned and anything it owns is released, before the next line of Python runs. These are plain,
non-atomic C increments, which is one reason only one thread may run Python code at a time. Both
the freeing and the threading rule get posts of their own later in this series.
Leak one: an identity is an address
The documentation for id() makes a careful promise:
Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same
id()value.CPython implementation detail: This is the address of the object in memory.
The C behind it is builtin_id in Python/bltinmodule.c, which does nothing but
return PyLong_FromVoidPtr(v);: it converts the pointer to an integer. The phrase “non-overlapping
lifetimes” is doing a lot of work there:
print([id(object()) for _ in range(4)])
print(id(object()) == id(object()))
o = object()
print(repr(o), hex(id(o)))
print("id(int) =", hex(id(int)), " id(None) =", hex(id(None)))
$ python3 ids.py
[137718946312336, 137718946312336, 137718946312336, 137718946312336]
True
<object object at 0x7d4130dfb090> 0x7d4130dfb090
id(int) = 0x9db840 id(None) = 0x9dfba0
$ python3 ids.py | tail -1
id(int) = 0x9db840 id(None) = 0x9dfba0
Four different objects, one identity. Each object() is created, has its address taken, and is
freed before the next one is made, because nothing keeps a reference to it. The allocator hands the
same block straight back for the next one. id(object()) == id(object()) is True for the same
reason: the first object is dead before the second is born. Two objects that are never alive at
the same time are allowed to share an id, and in CPython they often do.
That matters whenever an id outlives its object. A cache keyed on id(obj) that doesn’t also keep
obj alive will, sooner or later, find a stale entry under a new object’s id and treat the new
object as the old one. The default repr is the same address (object_repr formats it with
"<%s object at %p>"), which is why the hex number in <object object at 0x...> matches id()
exactly.
The second run shows the other half. The address of int and of None is the same in every
process, because they are static variables in a non-PIE executable. An id() of a built-in type is
stable across runs, while the id of anything you create is not. Neither is part of the language.
Other Python implementations, such as PyPy and Jython, move objects in memory as their garbage
collectors run. There, id() is a number they hand out and look after, which costs them work CPython
never does.
Leak two: the small integers are a C array
Two integers with the same value are equal. Whether they are the same object is up to the implementation, and in CPython it depends on the value:
import sys
a, b = int("256"), int("256")
print("int('256') is int('256'):", a is b)
a, b = int("257"), int("257")
print("int('257') is int('257'):", a is b)
print("id(1) - id(0) =", id(1) - id(0))
print("id(256) - id(0) =", id(256) - id(0), "=", (id(256) - id(0)) // 32, "* 32")
print("id(-5) - id(0) =", id(-5) - id(0))
print("id(int('257')) - id(0) =", id(int("257")) - id(0))
for n in (0, 1, 2, 100, 256):
print("references to %3d: %d" % (n, sys.getrefcount(n)))
$ python3 smallints.py
int('256') is int('256'): True
int('257') is int('257'): False
id(1) - id(0) = 32
id(256) - id(0) = 8192 = 256 * 32
id(-5) - id(0) = -160
id(int('257')) - id(0) = 128818538354128
references to 0: 447
references to 1: 807
references to 2: 103
references to 100: 11
references to 256: 26
Parsing "256" twice gives the same object, while "257" gives two. And the addresses of the
small integers are not scattered around the heap. They are exactly 32 bytes apart, in order, from
−5 up to 256. This is a C array, and here it is in Objects/longobject.c:
#define NSMALLPOSINTS 257
#define NSMALLNEGINTS 5
static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
static PyObject *
get_small_int(sdigit ival)
{
PyObject *v;
assert(-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS);
v = (PyObject *)&small_ints[ival + NSMALLNEGINTS];
Py_INCREF(v);
...
return v;
}
When the interpreter starts, it fills in 262 integer objects, −5 through 256, in a static array.
Every function that makes an integer from a C value, such as PyLong_FromLong, starts with
CHECK_SMALL_INT(ival), which returns an element of this array if the value is in range. The
elements are 32 bytes apart, not 28, because the C compiler pads each PyLongObject to a multiple
of eight bytes so that the next one’s pointer fields are aligned. id(n) − id(0) == 32 * n holds
for every cached n, which is pointer arithmetic on a C array, visible from Python. 257 is past the
end of the array, so int("257") allocates a new object on the heap, a hundred terabytes of address
space away from the array.
The reference counts show how heavily these few objects are shared. While this script ran, 0 had
447 references and 1 had 807. Every module’s constants, every range that starts at 0, every
len() of a short list and every loop counter points into this array. The chart below counts the
references to each integer from −5 to 299 in a fresh interpreter. None of the cached integers has
fewer than one, because the cache keeps a reference to each element for itself: _PyLong_Init sets
every count to 1 when the interpreter starts and never gives that reference up, which is also why
these objects are never freed. Past 256 there is nothing to share: each int() call makes a new
object, and nothing else refers to it.
References the interpreter holds to each integer
In a fresh Python 3.6.5, for every integer from −5 to 299. The cached ones are shared by the whole process; past 256 nothing is shared.
Hover or focus the chart to read a value.
Table of every value
| n | references |
|---|---|
| -5 | 2 |
| -4 | 1 |
| -3 | 3 |
| -2 | 5 |
| -1 | 46 |
| 0 | 553 |
| 1 | 880 |
| 2 | 136 |
| 3 | 54 |
| 4 | 80 |
| 5 | 38 |
| 6 | 32 |
| 7 | 19 |
| 8 | 74 |
| 9 | 16 |
| 10 | 19 |
| 11 | 16 |
| 12 | 11 |
| 13 | 13 |
| 14 | 11 |
| 15 | 9 |
| 16 | 31 |
| 17 | 11 |
| 18 | 9 |
| 19 | 9 |
| 20 | 10 |
| 21 | 8 |
| 22 | 7 |
| 23 | 11 |
| 24 | 17 |
| 25 | 7 |
| 26 | 7 |
| 27 | 7 |
| 28 | 7 |
| 29 | 9 |
| 30 | 12 |
| 31 | 8 |
| 32 | 23 |
| 33 | 5 |
| 34 | 7 |
| 35 | 7 |
| 36 | 5 |
| 37 | 5 |
| 38 | 5 |
| 39 | 5 |
| 40 | 7 |
| 41 | 2 |
| 42 | 5 |
| 43 | 5 |
| 44 | 5 |
| 45 | 5 |
| 46 | 5 |
| 47 | 5 |
| 48 | 6 |
| 49 | 6 |
| 50 | 6 |
| 51 | 6 |
| 52 | 6 |
| 53 | 7 |
| 54 | 6 |
| 55 | 6 |
| 56 | 9 |
| 57 | 6 |
| 58 | 2 |
| 59 | 5 |
| 60 | 6 |
| 61 | 5 |
| 62 | 5 |
| 63 | 5 |
| 64 | 32 |
| 65 | 11 |
| 66 | 9 |
| 67 | 9 |
| 68 | 9 |
| 69 | 9 |
| 70 | 9 |
| 71 | 9 |
| 72 | 12 |
| 73 | 9 |
| 74 | 9 |
| 75 | 9 |
| 76 | 9 |
| 77 | 9 |
| 78 | 9 |
| 79 | 6 |
| 80 | 6 |
| 81 | 6 |
| 82 | 6 |
| 83 | 6 |
| 84 | 6 |
| 85 | 6 |
| 86 | 6 |
| 87 | 6 |
| 88 | 8 |
| 89 | 6 |
| 90 | 6 |
| 91 | 5 |
| 92 | 6 |
| 93 | 5 |
| 94 | 5 |
| 95 | 8 |
| 96 | 5 |
| 97 | 6 |
| 98 | 6 |
| 99 | 6 |
| 100 | 6 |
| 101 | 6 |
| 102 | 6 |
| 103 | 7 |
| 104 | 7 |
| 105 | 9 |
| 106 | 6 |
| 107 | 6 |
| 108 | 7 |
| 109 | 6 |
| 110 | 7 |
| 111 | 7 |
| 112 | 6 |
| 113 | 6 |
| 114 | 7 |
| 115 | 10 |
| 116 | 6 |
| 117 | 6 |
| 118 | 6 |
| 119 | 6 |
| 120 | 8 |
| 121 | 6 |
| 122 | 6 |
| 123 | 5 |
| 124 | 5 |
| 125 | 5 |
| 126 | 5 |
| 127 | 8 |
| 128 | 27 |
| 129 | 5 |
| 130 | 5 |
| 131 | 5 |
| 132 | 4 |
| 133 | 1 |
| 134 | 1 |
| 135 | 1 |
| 136 | 1 |
| 137 | 1 |
| 138 | 1 |
| 139 | 1 |
| 140 | 1 |
| 141 | 1 |
| 142 | 1 |
| 143 | 1 |
| 144 | 1 |
| 145 | 1 |
| 146 | 1 |
| 147 | 1 |
| 148 | 1 |
| 149 | 1 |
| 150 | 1 |
| 151 | 1 |
| 152 | 1 |
| 153 | 1 |
| 154 | 1 |
| 155 | 1 |
| 156 | 1 |
| 157 | 1 |
| 158 | 1 |
| 159 | 1 |
| 160 | 1 |
| 161 | 1 |
| 162 | 1 |
| 163 | 1 |
| 164 | 1 |
| 165 | 1 |
| 166 | 1 |
| 167 | 1 |
| 168 | 1 |
| 169 | 1 |
| 170 | 1 |
| 171 | 1 |
| 172 | 1 |
| 173 | 1 |
| 174 | 1 |
| 175 | 1 |
| 176 | 1 |
| 177 | 1 |
| 178 | 1 |
| 179 | 1 |
| 180 | 1 |
| 181 | 4 |
| 182 | 1 |
| 183 | 1 |
| 184 | 1 |
| 185 | 1 |
| 186 | 1 |
| 187 | 1 |
| 188 | 1 |
| 189 | 1 |
| 190 | 1 |
| 191 | 1 |
| 192 | 1 |
| 193 | 1 |
| 194 | 1 |
| 195 | 1 |
| 196 | 1 |
| 197 | 1 |
| 198 | 1 |
| 199 | 1 |
| 200 | 1 |
| 201 | 1 |
| 202 | 1 |
| 203 | 1 |
| 204 | 1 |
| 205 | 1 |
| 206 | 1 |
| 207 | 1 |
| 208 | 1 |
| 209 | 1 |
| 210 | 1 |
| 211 | 1 |
| 212 | 1 |
| 213 | 1 |
| 214 | 1 |
| 215 | 1 |
| 216 | 1 |
| 217 | 1 |
| 218 | 1 |
| 219 | 1 |
| 220 | 1 |
| 221 | 1 |
| 222 | 1 |
| 223 | 1 |
| 224 | 1 |
| 225 | 1 |
| 226 | 1 |
| 227 | 1 |
| 228 | 1 |
| 229 | 1 |
| 230 | 1 |
| 231 | 1 |
| 232 | 1 |
| 233 | 1 |
| 234 | 1 |
| 235 | 1 |
| 236 | 1 |
| 237 | 1 |
| 238 | 1 |
| 239 | 1 |
| 240 | 1 |
| 241 | 1 |
| 242 | 1 |
| 243 | 1 |
| 244 | 1 |
| 245 | 1 |
| 246 | 1 |
| 247 | 1 |
| 248 | 1 |
| 249 | 1 |
| 250 | 1 |
| 251 | 1 |
| 252 | 1 |
| 253 | 1 |
| 254 | 1 |
| 255 | 4 |
| 256 | 27 |
| 257 | 0 |
| 258 | 0 |
| 259 | 0 |
| 260 | 0 |
| 261 | 0 |
| 262 | 0 |
| 263 | 0 |
| 264 | 0 |
| 265 | 0 |
| 266 | 0 |
| 267 | 0 |
| 268 | 0 |
| 269 | 0 |
| 270 | 0 |
| 271 | 0 |
| 272 | 0 |
| 273 | 0 |
| 274 | 0 |
| 275 | 0 |
| 276 | 0 |
| 277 | 0 |
| 278 | 0 |
| 279 | 0 |
| 280 | 0 |
| 281 | 0 |
| 282 | 0 |
| 283 | 0 |
| 284 | 0 |
| 285 | 0 |
| 286 | 0 |
| 287 | 0 |
| 288 | 0 |
| 289 | 0 |
| 290 | 0 |
| 291 | 0 |
| 292 | 0 |
| 293 | 0 |
| 294 | 0 |
| 295 | 0 |
| 296 | 0 |
| 297 | 0 |
| 298 | 0 |
| 299 | 0 |
Each value is sys.getrefcount(int(s)) − 2, counted from inside one script; another program imports other modules and holds other references. No cached integer has fewer than 1: the cache keeps a reference to every element for itself. The scale is logarithmic in 1 + references.
Constants share too, but differently
There is a second reason two equal integers can be one object, and it catches people who test the cache at the interactive prompt:
x = 257
y = 257
print("same line-pair in one module:", x is y)
ns = {}
exec("a = 257", ns)
exec("b = 257", ns)
print("two separate compiles: ", ns["a"] is ns["b"])
code = compile("p = 257\nq = 257", "<two lines>", "exec")
print("co_consts of one compile: ", code.co_consts)
$ python3 constants.py
same line-pair in one module: True
two separate compiles: False
co_consts of one compile: (257, None)
The compiler collects a code block’s constants into a tuple, co_consts, and stores each distinct
value once. Two 257 literals in one module compile to a single entry, so both names end up bound to
the same object, even though 257 is not cached. Two separate compilations each make their own. The
interactive prompt compiles each line you type separately, so there x = 257 and y = 257 on two
lines give two objects, while the same lines in a file give one. None of this is Python semantics. It
is what one compiler does with its constant table, and it can change from release to release.
The practical rule is the one the language always had: is asks whether two references point to
the same object, and the answer for equal integers, or equal strings, is an implementation detail.
Use == for values. The cache just makes the wrong test pass often enough to ship.
Leak three: −1 is taken
print("hash(1) =", hash(1))
print("hash(-1) =", hash(-1))
print("hash(-2) =", hash(-2))
print("hash(-1.0) =", hash(-1.0))
class Minus:
def __hash__(self):
return -1
print("hash(Minus()) =", hash(Minus()))
d = {-1: "minus one", -2: "minus two"}
print(d[-1], "/", d[-2])
$ python3 hashes.py
hash(1) = 1
hash(-1) = -2
hash(-2) = -2
hash(-1.0) = -2
hash(Minus()) = -2
minus one / minus two
The hash of a small integer is the integer itself, except for −1. Even a class whose __hash__
returns −1 gets −2 from hash(). The reason is the C signature of the hash slot, in
Include/object.h:
typedef Py_hash_t (*hashfunc)(PyObject *);
A C function returns one value. CPython’s convention for functions that return a number is that
−1 means “an exception was raised, check the error indicator”. Hashing can fail (a list is
unhashable, and a user’s __hash__ can raise anything), so −1 must be reserved for failure, and no
successful hash may ever be −1. Every hash function in CPython has to avoid it, and they all turn −1
into −2. For
integers it’s a special case at the top of long_hash:
i = Py_SIZE(v);
switch(i) {
case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
case 0: return 0;
case 1: return v->ob_digit[0];
}
A one-digit negative number has ob_size −1; if its digit is 1, the number is −1 and the hash is
−2. Floats do the same at the end of _Py_HashDouble (if (x == (Py_uhash_t)-1) x = (Py_uhash_t)-2;), which keeps hash(-1.0) == hash(-1) as the language requires for equal numbers.
Classes written in Python go through slot_tp_hash in Objects/typeobject.c, which ends with:
/* -1 is reserved for errors. */
if (h == -1)
h = -2;
So −1 and −2 collide in every dict and set, always. That costs nothing that matters: dicts compare keys for equality after matching hashes, so the last line of output finds both keys. But it shows the C calling convention, a return value doubling as an error flag, leaking all the way up into a number that Python programs can print.
Leak four: immutable by agreement
Python integers are immutable: no operation changes the value of an existing integer object.
That is a rule the C code follows, not something the memory enforces. The integer 7 lives in that
static array, its digit is four ordinary bytes, and ctypes can write as well as read. The C API
documentation for PyLong_FromLong, in the 3.6 manual, already knows:
The current implementation keeps an array of integer objects for all integers between
-5and256, when you create an int in that range you actually just get back a reference to the existing object. So it should be possible to change the value of1. I suspect the behaviour of Python in this case is undefined. :-)
It is possible:
import ctypes, struct
seven = 7
digit_addr = id(seven) + 24 # ob_digit[0] of the cached 7
ctypes.memmove(digit_addr, struct.pack("<I", 8), 4)
print(7)
print(len("abcdefg"))
print(3 + 4)
print(7 == 8)
$ python3 mutate.py
8
8
8
True
Do not run this anywhere you care about. It overwrites ob_digit[0] of the shared 7 with an 8,
and after that every 7 in the process is 8. The literal 7 in print(7) is a compile-time
constant, and the function that turned the source text 7 into an object returns the cached object
for small values.
len("abcdefg") computes 7 in C and turns it into an object with PyLong_FromSsize_t, which
returns the cached object, now holding 8. The compiler computed 3 + 4 before the program ran,
and the 7 it stored as a constant is the cached object too. And 7 == 8 compares two objects that both hold 8.
The program survived because it exited immediately. A longer one would not have: 7 is used inside the interpreter itself, as list indices, string lengths and loop bounds, and every one of them is now wrong by one. It’s a party trick, but the mechanism is the point of this post. “Immutable” means the code that implements integers never writes to one after creating it. The memory is as writable as any other, so the guarantee holds only as long as nothing reaches under the interpreter, and any C extension module can.
What a million integers cost
These layouts add up. Here is a million distinct integers in a list, measured with tracemalloc
(which records every allocation the interpreter makes), next to the same million values packed as C
long longs in the standard array module:
import sys, tracemalloc
from array import array
N = 1000000
tracemalloc.start()
ints = [i for i in range(1000, 1000 + N)] # a million distinct int objects
listed = tracemalloc.get_traced_memory()[0]
tracemalloc.stop()
tracemalloc.start()
packed = array("q", range(1000, 1000 + N)) # a million C long longs
arr = tracemalloc.get_traced_memory()[0]
tracemalloc.stop()
print("list of ints : %10d bytes %5.1f per element" % (listed, listed / N))
print(" of which the list's pointer array: %d" % (sys.getsizeof(ints) - 64))
print("array('q') : %10d bytes %5.1f per element" % (arr, arr / N))
$ python3 cost.py
list of ints : 36697400 bytes 36.7 per element
of which the list's pointer array: 8697400
array('q') : 8183800 bytes 8.2 per element
The list is 36.7 bytes per number: 28 for each integer object and 8.7 for the pointer to it (eight bytes, plus the spare slots of a list that grew by appending). The array stores the same values in 8.2 bytes each, as raw C integers with no header, plus the slack of its own growth. The array is also faster to scan, because its values sit side by side in memory instead of behind a pointer each.
Even 36.7 is an underestimate. tracemalloc records the size the interpreter asked for, and
CPython’s own allocator serves small requests in fixed size classes. In 3.6 they are multiples of
eight bytes (ALIGNMENT 8 in Objects/obmalloc.c), so each 28-byte integer really occupies a
32-byte block. That allocator gets a post of its own.
What we covered
- CPython is a C program, and Python’s built-in types are C structs and functions inside it.
intis the global variablePyLong_Type, at a fixed address in Ubuntu’s non-PIE build. - Every object starts with
ob_refcntandob_type, a 16-bytePyObject. Variable-sized objects addob_sizeto make a 24-bytePyVarObject. A Python variable is a name bound to a pointer to one of these. - An integer is a sign in
ob_sizeplus digits in base 230: 24 bytes for zero, 28 up to 230 − 1, and 4 more for every 30 bits after that. A float is a Cdoublebehind a 16-byte header. - Tuples hold pointers inline. Lists hold a pointer to a separately allocated, over-allocated array
that moves when it grows. Containers carry a 24-byte cycle-collector header before
id(), whichsys.getsizeofcounts, while it never counts the objects a container points to. - Reference counts change on every bind and unbind, with plain non-atomic increments, and an object is freed the moment its count reaches zero.
- Four leaks:
id()is an address and is reused as soon as an object dies; the integers −5 to 256 are one static C array, soisworks on them by accident; −1 is never a hash because C returns −1 for errors; and immutability is a convention thatctypescan break.
The next post follows the other half of the picture: what the interpreter does with these objects when it runs a function, from source text to bytecode to the C loop that executes it.
A note on the evidence
What I ran, and where. Every listing in this post is pasted from a real run on Ubuntu 18.04’s
release userland: a minimal 18.04 root built from the bionic release archive only, so every package
is at its release-day version. That means python3 and python3.6 3.6.5-3 (built Apr 1 2018,
[GCC 7.3.0]), python3-dev 3.6.5-3, gcc 7.3.0-16ubuntu3, gdb 8.1-0ubuntu3 and libc6 2.27-3ubuntu1.
I ran it as a chroot on a 64-bit x86 machine, so the kernel underneath was the host’s, not 18.04’s.
Nothing in this post depends on the kernel beyond the randomised placement of the heap, which every
recent Linux does. Each script was extracted from this page and run as shown, and embed.c was
compiled with the command shown.
Several runs, not one. Each script ran in its own process, so heap addresses differ from listing
to listing, and two listings never share an address unless the text says why. The reference counts
of small integers depend on what the process has imported. They were 447 for 0 in smallints.py,
and 553 in the run that produced the chart, which counts from inside a different script. That
script walks prepared strings and stores its counts in an array('q'), so that its own loop holds
no integer objects. My first version kept a loop counter and a list of results, which added
references to the very integers it was counting. The
addresses of PyLong_Type, PyFloat_Type and _Py_NoneStruct were the same in every run of
/usr/bin/python3.6. The embedded program has its own copy of the library and its own addresses.
What I worked out rather than read. The decoding of the ob_type, digit and float bytes is by
hand, from the struct definitions, and the scripts’ own struct decoding agrees with it. That the
list’s gc_next points at the generation-0 list head follows from the _PyObject_GC_TRACK macro in
Include/objimpl.h (a new object is appended at the tail, so its next node is the head) and from the
script finding no object whose header sits at that address. I didn’t print the head’s address from C
to confirm it.
What I cited rather than ran. The struct definitions, get_small_int, long_hash,
slot_tp_hash, _Py_HashDouble, _PySys_GetSizeOf, list_resize, builtin_id, object_repr,
PyFloat_MAXFREELIST and ALIGNMENT are quoted from the CPython source at the v3.6.5 tag, which is
what Ubuntu’s 3.6.5-3 package was built from. The documentation quotes are from the 3.6 manual at the
same tag. The change to 30-bit digits in Python 3.1 is from that release’s “What’s New”.
What I’d still change. These layouts are CPython 3.6’s on a 64-bit build. On a 32-bit build the
headers are smaller and the digits are 15 bits, and a build configured with --with-pydebug
(Ubuntu’s python3-dbg) adds two pointers to every object, so every offset in this post moves.
ctypes.string_at would also happily read past the end of an object if I gave it the wrong size.
Every size here came from sys.getsizeof or the struct definitions, but nothing checked that for me.
Every Value Is a Pointer to a Struct