← Writing

Dicts All the Way Down

18 min readSystemsPythonCpythonCDictHash-Tables
Contents

A Python 3.7 dict holding a million integers is 41,943,144 bytes. Delete every key and it is still 41,943,144 bytes. Add one key back and it’s the same. The dict has no entries left, but it keeps the table it grew for a million, and the only way to get the memory back is to copy it: dict(d) is 240 bytes. That is one of several things about dicts that the language doesn’t say and the C code decides, and dicts matter more than any other structure in CPython, because the interpreter is built out of them: module globals, class namespaces, instance attributes and keyword arguments are all dicts.

This post reads a dict’s table straight from memory, reproduces where each key lands by running CPython’s probing rule in Python, watches the table grow, shows why deleting doesn’t shrink it, measures how instances share their keys until something breaks it, and times the cache that makes method lookup fast until a class changes.

This is Part 8 of a series on the CPython runtime. Part 2 timed LOAD_GLOBAL and LOAD_ATTR, and Part 7 showed where string hashes come from. It is written for Python programmers who have written a little C. Everything here ran on CPython 3.7.3, released on 25 March and built from its tag with Ubuntu 18.04’s gcc 7.3.0. The note at the end says exactly where and how.

Two arrays

Before Python 3.6, a dict was one array of (hash, key, value) entries, mostly empty, because a hash table has to keep about a third of its slots free to stay fast. In December 2012 Raymond Hettinger proposed splitting it in two on python-dev: a small array of indices that is the actual hash table, and a dense array of entries in insertion order. PyPy shipped the idea in 2015, and CPython 3.6 adopted it, by INADA Naoki. The layout is drawn at the top of Objects/dictobject.c:

/* PyDictKeysObject

This implements the dictionary's hashtable.

As of Python 3.6, this is compact and ordered. Basic idea is described here:
* https://mail.python.org/pipermail/python-dev/2012-December/123028.html
* https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html

layout:

+---------------+
| dk_refcnt     |
| dk_size       |
| dk_lookup     |
| dk_usable     |
| dk_nentries   |
+---------------+
| dk_indices    |
|               |
+---------------+
| dk_entries    |
|               |
+---------------+

dk_indices is actual hashtable.  It holds index in entries, or DKIX_EMPTY(-1)
or DKIX_DUMMY(-2).
Size of indices is dk_size.  Type of each index in indices is vary on dk_size:

* int8  for          dk_size <= 128
* int16 for 256   <= dk_size <= 2**15
* int32 for 2**16 <= dk_size <= 2**31
* int64 for 2**32 <= dk_size

and each entry is a PyDictKeyEntry, from Objects/dict-common.h:

typedef struct {
    /* Cached hash code of me_key. */
    Py_hash_t me_hash;
    PyObject *me_key;
    PyObject *me_value; /* This field is only meaningful for combined tables */
} PyDictKeyEntry;

The PyDictObject itself holds ma_used (the number of items), a version tag, a pointer to the keys object (ma_keys), and ma_values, which is NULL except for the split tables described later. A small reader, using Part 1’s ctypes method, decodes all of it:

import ctypes, struct

def q(addr, k=0):
    return struct.unpack("<q", ctypes.string_at(addr + 8 * k, 8))[0]

def keys_of(d):
    """Read a dict's PyDictObject and its PyDictKeysObject straight from memory."""
    ma_used, version, keys, values = (q(id(d), 2), q(id(d), 3), q(id(d), 4), q(id(d), 5))
    size, usable, nentries = q(keys, 1), q(keys, 3), q(keys, 4)
    width = 1 if size <= 0xff else 2 if size <= 0xffff else 4 if size <= 0xffffffff else 8
    fmt = {1: "b", 2: "h", 4: "i", 8: "q"}[width]
    indices = list(struct.unpack("<%d%s" % (size, fmt), ctypes.string_at(keys + 40, size * width)))
    entries_at = keys + 40 + size * width
    entries = [struct.unpack("<qqq", ctypes.string_at(entries_at + 24 * i, 24)) for i in range(nentries)]
    return {"ma_used": ma_used, "split": values != 0, "dk_size": size, "dk_usable": usable,
            "dk_nentries": nentries, "indices": indices, "entries": entries}

That’s dictmem.py. Here is a four-key dict, decoded, and then reproduced: the second half runs CPython’s probing rule on the stored hashes and checks that it puts every key exactly where the real table has it.

from dictmem import keys_of

d = {}
for word in ["red", "green", "blue", "cyan"]:
    d[word] = len(word)
k = keys_of(d)
print("ma_used %d  dk_size %d  dk_usable %d  dk_nentries %d  split %s" %
      (k["ma_used"], k["dk_size"], k["dk_usable"], k["dk_nentries"], k["split"]))
print("dk_indices:", k["indices"])
for i, (h, key, value) in enumerate(k["entries"]):
    name = [w for w in d if id(w) == key][0]
    print("entry %d: hash %20d (== hash(%r): %s)  key -> %r  value -> %d" %
          (i, h, name, h == hash(name), name, [v for v in d.values() if id(v) == value][0]))

# Where CPython's probing should have put each key, computed from the hashes alone
def slot(h, mask, used):
    perturb = h & 0xFFFFFFFFFFFFFFFF
    i = perturb & mask
    while i in used:
        perturb >>= 5
        i = (i * 5 + perturb + 1) & mask
    return i
used, mask = {}, k["dk_size"] - 1
for idx, (h, key, value) in enumerate(k["entries"]):
    used[slot(h, mask, used)] = idx
model = [used.get(i, -1) for i in range(k["dk_size"])]
print("model indices:", model, " matches memory:", model == k["indices"])
$ python3 layout.py
ma_used 4  dk_size 8  dk_usable 1  dk_nentries 4  split False
dk_indices: [3, 0, -1, 1, -1, -1, 2, -1]
entry 0: hash  5697751226910310737 (== hash('red'): True)  key -> 'red'  value -> 3
entry 1: hash  3222278684525075227 (== hash('green'): True)  key -> 'green'  value -> 5
entry 2: hash -3100224359639660074 (== hash('blue'): True)  key -> 'blue'  value -> 4
entry 3: hash  8399422293051681368 (== hash('cyan'): True)  key -> 'cyan'  value -> 4
model indices: [3, 0, -1, 1, -1, -1, 2, -1]  matches memory: True

Read it from the bottom up. The entries are in insertion order, red, green, blue, cyan, each with the key’s cached hash (the same as hash(name), as Part 7 promised) and pointers to the key and value. Iterating a dict walks this array, which is why dicts iterate in insertion order: it isn’t a feature added on top, it falls out of the layout. Since 3.7 the language guarantees it.

The hash table is the 8-byte dk_indices array. Each slot holds an index into the entries, or −1 for empty. Slot 0 holds 3, so cyan lives there. To find blue, CPython takes its hash modulo 8 (the low three bits), lands on a slot, and if that slot points at a different key, probes another slot by the rule the model reproduces. The table is four entries in 8 one-byte indices plus 5 × 24-byte entries, where the old layout needed 8 × 24-byte slots. dk_usable 1 means one more key fits before the table must grow.

This run’s hashes, and therefore its table, are this process’s. Run it again and Part 7’s hash randomisation puts the keys in different slots, but the model and the memory still agree, because the model doesn’t guess. It applies the same rule to the same stored hashes.

Four keys into an eight-slot table

The hashes are the ones the dict stored in one run; each step places one key by CPython's probe.

dk_indices (the hash table)

slot 03
slot 10
slot 2-1
slot 31
slot 4-1
slot 5-1
slot 62
slot 7-1

dk_entries (in insertion order)

In this run each key found its first slot free; hashes change from run to run, and in other runs some keys collide and probe. −1 is an empty slot. A lookup follows exactly the same path as the insertion did, stopping at the slot whose entry has the key, or at an empty slot.

How it grows

A table that’s two-thirds full is resized. The new size is the smallest power of two at least GROWTH_RATE(d), which in 3.7 is ma_used * 3. Here’s every resize up to two thousand integers:

import sys
from dictmem import keys_of

d, last = {}, None
print("%6s %9s %8s %10s" % ("items", "getsizeof", "dk_size", "capacity"))
for n in range(0, 2000):
    d[n] = n
    k = keys_of(d)
    if k["dk_size"] != last:                    # print only when the table is resized
        print("%6d %9d %8d %10d" % (len(d), sys.getsizeof(d), k["dk_size"], k["dk_usable"] + k["dk_nentries"]))
        last = k["dk_size"]
$ python3 growth.py
 items getsizeof  dk_size   capacity
     1       240        8          5
     6       368       16         10
    11       648       32         21
    22      1184       64         42
    43      2280      128         85
    86      4704      256        170
   171      9320      512        341
   342     18528     1024        682
   683     36968     2048       1365
  1366     73824     4096       2730

The 6th key doesn’t fit in a table of 8, whose capacity is 5, so the table becomes 16, since 5 × 3 = 15, rounded up. The 11th makes it 32, the 22nd 64. Each step a bit more than doubles the memory, and just after a resize a dict is a little over a third full. getsizeof here is the dict object (48 bytes) plus its keys object, and the steps show the 3.7 layout exactly: 368 = 48 + 40 (keys header) + 16 one-byte indices + 10 × 24-byte entries + 24 (GC header).

Deleting frees nothing

Deletion has a problem that insertion doesn’t. If blue was found by probing past green’s slot, and green is deleted, a lookup for blue must still probe past that slot, so the slot can’t simply become empty again. CPython marks it DKIX_DUMMY (−2), a tombstone that means “keep probing”, and leaves the entry’s position in the dense array used:

import sys
from dictmem import keys_of

d = {i: None for i in range(1000000)}
print("1M keys:          getsizeof %9d   ma_used %7d  dk_nentries %7d" % (sys.getsizeof(d), keys_of(d)["ma_used"], keys_of(d)["dk_nentries"]))
for i in range(1000000):
    del d[i]
print("all deleted:      getsizeof %9d   ma_used %7d  dk_nentries %7d" % (sys.getsizeof(d), keys_of(d)["ma_used"], keys_of(d)["dk_nentries"]))
d["x"] = 1
print("one key added:    getsizeof %9d   ma_used %7d  dk_nentries %7d" % (sys.getsizeof(d), keys_of(d)["ma_used"], keys_of(d)["dk_nentries"]))
d = dict(d)
print("copied: dict(d):  getsizeof %9d" % sys.getsizeof(d))
$ python3 deletion.py
1M keys:          getsizeof  41943144   ma_used 1000000  dk_nentries 1000000
all deleted:      getsizeof  41943144   ma_used       0  dk_nentries 1000000
one key added:    getsizeof  41943144   ma_used       1  dk_nentries 1000001
copied: dict(d):  getsizeof       240

Every key deleted, ma_used zero, and the table is the same 42 MB. The million entries are still there as tombstones, dk_nentries still counts them, and the dict holds the memory. Adding a key doesn’t help: the new entry goes on the end, at position 1,000,000, because entries are only ever appended. The table is rebuilt only when it fills up, and at that point the rebuild sizes it for the live keys. Until then a dict that once held a million items keeps the space for a million, whatever it holds now.

dict(d) builds a new dict from the live items, a single key here, and the old table is freed. For long-lived dicts that churn (caches, registries, session tables), a periodic copy is the only way to give the memory back. Nothing in the language suggests you’d need one.

Instances share their keys

Every instance of an ordinary class has a __dict__, and most instances of a class have the same attribute names, set in the same order in __init__. Python 3.3’s PEP 412, “Key-Sharing Dictionary”, exploits that: the class keeps one keys object, and each instance’s dict is a split table that points to the shared keys and carries only its own array of values (ma_values). That’s the split field the reader reports. What it costs, and what breaks it, measured with tracemalloc over 100,000 instances:

import random, sys, tracemalloc
from dictmem import keys_of

class Point:
    def __init__(self, x, y, z):
        self.x = x; self.y = y; self.z = z

class Shuffled:
    def __init__(self, order):
        for name in order:
            setattr(self, name, 0)

class Slotted:
    __slots__ = ("x", "y", "z")
    def __init__(self, x, y, z):
        self.x = x; self.y = y; self.z = z

N = 100000
def per_object(make):
    tracemalloc.start()
    objs = [make(i) for i in range(N)]
    used = tracemalloc.get_traced_memory()[0]
    tracemalloc.stop()
    return objs, used / N

def deleted(i):
    p = Point(i, i, i)
    del p.z                                         # one attribute deleted
    return p

def late(i):
    p = Point(i, i, i)
    p.extra = 1                                     # one attribute added after __init__
    return p

orders = [random.sample("xyz", 3) for _ in range(N)]
for label, make in [("Point, attributes set in __init__", lambda i: Point(i, i, i)),
                    ("Point + one attribute added later", late),
                    ("Point with one attribute deleted", deleted),
                    ("same 3 names, random order", lambda i: Shuffled(orders[i])),
                    ("__slots__", lambda i: Slotted(i, i, i))]:
    objs, each = per_object(make)
    o = objs[-1]
    detail = ("__dict__ %3d bytes, split %s" % (sys.getsizeof(o.__dict__), keys_of(o.__dict__)["split"])
              if hasattr(o, "__dict__") else "no __dict__")
    print("%-34s %6.1f bytes per object   (%s)" % (label, each, detail))
$ python3 sharing.py
Point, attributes set in __init__   204.2 bytes per object   (__dict__ 112 bytes, split True)
Point + one attribute added later   204.2 bytes per object   (__dict__ 112 bytes, split True)
Point with one attribute deleted    332.1 bytes per object   (__dict__ 240 bytes, split False)
same 3 names, random order          304.2 bytes per object   (__dict__ 240 bytes, split False)
__slots__                           100.2 bytes per object   (no __dict__)

(Each figure includes the three attribute values, which are small cached integers in some rows and not in others, so the differences matter more than the totals.)

  • Shared, the normal case: 204 bytes per object, and a 112-byte __dict__ that is a split table.
  • An attribute added later to every instance, in the same order, still shares. The shared keys grew by one name, and every instance’s values array had room for it.
  • One attribute deleted: 332 bytes, and split False. Deletion from a split table converts that instance’s dict to an ordinary combined one, with its own copy of the keys.
  • The same three names in random order: 304 bytes, and not split. A split table requires that the keys were inserted in the shared order, so an instance that sets y before x gets its own table.
  • __slots__: 100 bytes, with no dict at all. The attributes are stored at fixed offsets in the object, through descriptors on the class.

None of this is visible to the program. Two classes with identical behaviour can differ by 50% in memory per instance because one sets its attributes in a fixed order and the other doesn’t, or because some code path does del self.cache instead of self.cache = None.

How big dicts get

CPython 3.7.3: a dict's size at every resize, and the memory per instance for five ways to hold three attributes.

getsizeof(dict) as it grows

Bytes per object, 100,000 objects

attributes set in __init__split: shares keys
204 B
+ one attribute added latersplit: shares keys
204 B
one attribute deletedcombined: own keys
332 B
same 3 names, random ordercombined: own keys
304 B
__slots__no __dict__
100 B

Hover or focus a point or a bar for details.

The method cache

Part 2 found that obj.method costs a lookup in the type before the instance. In a class hierarchy that lookup walks the method resolution order, checking the dict of every class until it finds the name, which could make method calls slower the deeper the hierarchy. CPython avoids that with a global cache in front of _PyType_Lookup, in Objects/typeobject.c:

PyObject *
_PyType_Lookup(PyTypeObject *type, PyObject *name)
{
    PyObject *res;
    int error;
    unsigned int h;

    if (MCACHE_CACHEABLE_NAME(name) &&
        PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
        /* fast path */
        h = MCACHE_HASH_METHOD(type, name);
        if (method_cache[h].version == type->tp_version_tag &&
            method_cache[h].name == name) {
            return method_cache[h].value;
        }
    }
    ...
    res = find_name_in_mro(type, name, &error);

The cache has 4,096 entries (MCACHE_SIZE_EXP 12), keyed by the type’s version tag and the name. Every type has a version tag, and any change to a type’s dictionary, assigning, deleting or adding a class attribute, calls PyType_Modified, which invalidates the tag of that type and of every subclass, so cached lookups for them miss until the tags are reassigned. Here’s a class 31 levels deep, with the method defined at the top:

import timeit

class Base:
    def method(self):
        pass
classes = [Base]
for i in range(30):
    classes.append(type("C%d" % i, (classes[-1],), {}))
Deep = classes[-1]
obj = Deep()

def lookup(n):
    for _ in range(n):
        obj.method

def lookup_while_mutating(n):
    for i in range(n):
        obj.method
        Base.counter = i                   # assigning a class attribute invalidates the cache

def mutating_only(n):
    for i in range(n):
        Base.counter = i

N = 1000000
for f in (lookup, lookup_while_mutating, mutating_only):
    best = min(timeit.repeat(lambda: f(N), number=1, repeat=5))
    print("%-22s %6.1f ns per iteration" % (f.__name__, best / N * 1e9))
$ python3 mcache.py
lookup                   19.9 ns per iteration
lookup_while_mutating   432.4 ns per iteration
mutating_only            43.3 ns per iteration

With the cache warm, looking up a method defined 31 classes up costs 20 nanoseconds, the same as for a method on the instance’s own class. Assigning Base.counter in the same loop costs 43 ns on its own, but makes the lookup take about 390 ns more, because every assignment to Base invalidates the version tags of all 31 classes below it, and each lookup then misses the cache, walks the MRO, and refills it. That’s a 20-fold slowdown of an attribute access caused by an unrelated assignment, and it’s the pattern of class-level counters, registries and caches written as class attributes and updated in hot code.

What we covered

  • Since 3.6, a dict is an index table (one to eight bytes per slot) over a dense entries array in insertion order. Iteration order falls out of the layout.
  • Keys are placed by open addressing with the recurrence j = 5j + 1 + perturb, which a few lines of Python reproduce exactly from the stored hashes.
  • The table is kept at most two-thirds full and grows to the next power of two above three times the item count: 8, 16, 32 slots and on.
  • Deleting leaves tombstones and keeps the table. A dict emptied of a million keys stayed at 42 MB until it was copied.
  • Instances of a class share one keys object (PEP 412), at 204 bytes per small object here, until an attribute is deleted (332 bytes) or attributes are set in a different order (304). __slots__ needs 100.
  • A 4,096-entry cache keyed by type version tags makes method lookup independent of hierarchy depth. Assigning one class attribute per loop invalidated it and made a lookup twenty times slower.

The next post leaves containers for numbers: what CPython does for 1 + 1, why integers that grow past 2³⁰ get slower, and where Python numbers and C numbers part company.

A note on the evidence

What I ran, and where. Everything ran on CPython 3.7.3, built from the v3.7.3 tag with Ubuntu 18.04’s gcc 7.3.0, on a minimal 18.04 userland from the release archive, as a chroot on a 64-bit x86 machine. Nothing here depends on the kernel. Each script was extracted from this page and run as shown.

The numbers. The table layout, sizes and tombstone counts are deterministic for this build, except the hashes and slot positions in layout.py, which change every run with string hash randomisation. The model matches the memory in every run, which is the claim. The per-object figures are tracemalloc totals divided by 100,000, so they include the objects’ attribute values and are the memory Python asked for, not the allocator’s rounding. The method-cache timings are the best of five runs on an idle machine.

What I worked out rather than read. The arithmetic of the 368-byte dict is from the struct layouts on this build. That a late attribute added to every instance keeps sharing, and a deletion doesn’t, is what this build did. I didn’t trace which branch of the split-table code took each decision. That the slow lookup walks all 31 classes is from find_name_in_mro, not from counting.

What I cited rather than ran. The C quoted here is from the v3.7.3 tag: Objects/dictobject.c, Objects/dict-common.h and Objects/typeobject.c. The history (Raymond Hettinger’s December 2012 python-dev proposal, PyPy’s 2015 implementation, INADA Naoki’s 3.6 implementation, PEP 412 in 3.3, the ordering guarantee in 3.7) is from those messages, PEPs and the 3.6 and 3.7 “What’s New”.

What I’d still change. The probing model covers inserts without deletions. A model of tombstones and of the specialised lookup functions (lookdict_unicode and friends) would let the same check cover every dict. And the per-object memory depends on the values stored. A version with identical values in every row would isolate the dict’s cost exactly.

More