4. Containers and Reference Counts

This chapter looks in more detail of how the Python C API works with different containers, such as tuple, list, set and dict [1]. It also clarifies and correct the Python documentation where that is inaccurate, incomplete or misleading. This also shows where the Python C API has some undocumented failure modes, some of which can lead to undefined behaviour.

This chapter includes examples and tests that you can step through to better understand the interplay between the container and the objects in that container.

Of particular interest are Setters, Getters and the behaviour of Py_BuildValue for each of those containers [2].

Note

The Python documentation for the Concrete Objects Layer has a general warning that passing NULL values into functions gives rise to undefined behaviour. This is not always the case and this chapter explores this in more detail than the official Python documentation.

4.1. Some Additional Terminology

As well as “New” References, “Stolen” References and “Borrowed” References described in the previous chapter some other behaviors of containers are worth defining when they interact with objects.

4.1.1. Discarded References

This is when a container has a reference to an object but is required to replace it with another object. In this case the container decrements the reference count of the original object before replacing it with the other object. This is to prevent a memory leak of the previous object.

Warning

If the the replacement object is the same as the existing object then very bad things might happen. For example see the warning in PyTuple_SetItem() PyTuple_SetItem() Replacement.

4.1.2. Abandoned References

This is when a container has a reference to an object but is required to replace it with another object. In this case the container does not decrement the reference count of the original object before replacing it with the other object. This will lead to a memory leak unless the replacement object is the same as the existing object. Of course if the original reference is NULL there is no leak.

An example of this is PyTuple_SET_ITEM() PyTuple_SET_ITEM() Replacement.

4.2. Exploring the CPython C API

The code in this chapter explores the CPython C API in several ways:

  • C code that can be stepped through in the debugger. This code is in src/cpy/Containers/DebugContainers.c. This uses asserts to check the results, particularly reference counts, so should always be compiled with -DDEBUG. The tests are exercised by src/main.c.

  • Test code is in src/cpy/RefCount/cRefCount.c which is built into the Python module cPyExtPatt.cRefCount. This can be run under pytest for multiple Python versions by build_all.sh.

  • A study of the Python source code.

  • A review of the Python C API documentation.

Note

The examples below use code that calls a function new_unique_string(). This function is designed to create a new, unique, PyObject (a string) that is never cached so always starts with a reference count of unity. The implementation is in src/cpy/Containers/DebugContainers.c and looks something like this:

static long debug_test_count = 0L;

PyObject *
new_unique_string(const char *function, const char *suffix) {
    if (suffix){
        return PyUnicode_FromFormat(
            "%s-%s-%ld", function, suffix, debug_test_count++
        );
    }
    return PyUnicode_FromFormat("%s-%ld", function, debug_test_count++);
}

Here is an example test function that checks that PyTuple_SetItem() steals a reference:

 1/**
 2 * A function that checks whether a tuple steals a reference when using PyTuple_SetItem.
 3 * This can be stepped through in the debugger.
 4 * asserts are use for the test so this is expected to be run in DEBUG mode.
 5 */
 6void dbg_PyTuple_SetItem_steals(void) {
 7    printf("%s():\n", __FUNCTION__);
 8    if (PyErr_Occurred()) {
 9        fprintf(stderr, "%s(): On entry PyErr_Print() %s#%d:\n", __FUNCTION__, __FILE_NAME__, __LINE__);
10        PyErr_Print();
11        return;
12    }
13    assert(!PyErr_Occurred());
14    Py_ssize_t ref_count;
15
16    PyObject *container = PyTuple_New(1);
17    assert(container);
18    ref_count = Py_REFCNT(container);
19    assert(ref_count == 1);
20
21    PyObject *value = new_unique_string(__FUNCTION__, NULL);
22    ref_count = Py_REFCNT(value);
23    assert(ref_count == 1);
24
25    if (PyTuple_SetItem(container, 0, value)) {
26        assert(0);
27    }
28    ref_count = Py_REFCNT(value);
29    assert(ref_count == 1);
30
31    PyObject *get_item = PyTuple_GET_ITEM(container, 0);
32    ref_count = Py_REFCNT(get_item);
33    assert(ref_count == 1);
34
35    Py_DECREF(container);
36    /* NO as container deals with this. */
37    /* Py_DECREF(value); */
38    assert(!PyErr_Occurred());
39}

Firstly Tuples, I’ll go into quite a lot of detail here because it is very similar to the C API for lists which I’ll cover with more brevity in a later section.

4.3. Tuples

The Python documentation for the Tuple C API is here.

Firstly setters, there are two APIs for setting an item in a tuple; PyTuple_SetItem() and PyTuple_SET_ITEM().

4.3.1. PyTuple_SetItem()

PyTuple_SetItem() (a C function) inserts an object into a tuple with error checking. This function returns non-zero on error, these are described below in PyTuple_SetItem() Failures. The failure of PyTuple_SetItem() has serious consequences for the value that is intended to be inserted.

4.3.1.1. PyTuple_SetItem() Basic Usage

PyTuple_SetItem() steals a reference, that is, the container assumes responsibility for freeing that value when the container is free’d (‘freeing’ meaning decrementing the reference count). For example:

PyObject *container = PyTuple_New(1); /* container ref count will be 1. */
PyObject *value = new_unique_string(__FUNCTION__, NULL); /* value ref count will be 1. */
PyTuple_SetItem(container, 0, value); /* value ref count will remain at 1. */
/* get_item == value and value ref count will be 1. */
PyObject *get_item = PyTuple_GET_ITEM(container, 0);
/* The contents of the container and value, will be decref'd
 * In this particular case both will go to zero and free'd. */
Py_DECREF(container);
/* Do not do this as the container has dealt with this. */
/* Py_DECREF(value); */

For code and tests see:

  • C: in src/cpy/Containers/DebugContainers.c:
    • dbg_PyTuple_SetItem_steals

  • CPython: in src/cpy/RefCount/cRefCount.c:
    • test_PyTuple_SetItem_steals()

  • Python: in tests/unit/test_c_ref_count.py:
    • test_PyTuple_SetItem_steals().

Whilst we are here this is an example of testing the behaviour by manipulating reference counts which we then check with assert(). The rationale is that you can’t check reference counts after an object is destroyed. For example:

PyObject *value = new_unique_string(__FUNCTION__, NULL);
assert(Py_REFCNT(value) == 1);
Py_DECREF(value);
/* This will fail, the reference count will have an arbitrary value. */
assert(Py_REFCNT(value) == 0);

Once an object has been free’d you can not rely on the reference count field. Instead, deliberately increment the reference count before the critical section and check it afterwards. For example:

PyObject *container = PyTuple_New(1);
PyObject *value = new_unique_string(__FUNCTION__, NULL);
assert(Py_REFCNT(value) == 1);
PyTuple_SetItem(container, 0, value);
assert(Py_REFCNT(value) == 1);
/* Increment the reference count so we can see destruction. */
Py_INCREF(value);
assert(Py_REFCNT(value) == 2);
/* Check destruction. */
Py_DECREF(container);
assert(Py_REFCNT(value) == 1);
/* Clean up. */
Py_DECREF(value);

4.3.1.2. PyTuple_SetItem() Replacement

What happens when you use PyTuple_SetItem() to replace an existing element in a tuple? PyTuple_SetItem() still steals a reference, but what happens to the original reference? Lets see:

PyObject *container = PyTuple_New(1); /* container ref count will be 1. */
PyObject *value_a = new_unique_string(__FUNCTION__, NULL);
/* value_a ref count will be 1. */
PyTuple_SetItem(container, 0, value_a); /* value_a ref count will remain 1. */
PyObject *value_b = new_unique_string(__FUNCTION__, NULL);
/* value_b ref count will be 1. */
PyTuple_SetItem(container, 0, value_b);
/* Now value_b ref count will remain 1 and value_a ref count will have been decremented
 * In this case value_a will have been free'd. */

Warning

What happens if you use PyTuple_SetItem() to replace a value with the same value? For example:

PyObject *container = PyTuple_New(1);
/* container ref count will be 1. */
PyObject *value = new_unique_string(__FUNCTION__, NULL);
/* value ref count will be 1. */
PyTuple_SetItem(container, 0, value);
/* value ref count is still 1 as it has been *stolen*. */

Now repeat the replacement:

/* Repeating the same call will only lead to trouble later on (maybe). */
PyTuple_SetItem(container, 0, value);
/* And this will segfault as, during execution, it will
 * try to decrement a value that does not exist. */
Py_DECREF(container);
/* So what is going on? */

What is happening is that the second time PyTuple_SetItem() is called it decrements the reference count of the existing member that happens to be value. In this case this brings value’s reference count from one down to zero At that point value is free’d. Then PyTuple_SetItem() blithely sets value which is now, likely, garbage.

This is not described in the Python documentation.

A simple change to PyTuple_SetItem() would prevent this from producing undefined behaviour by checking if the replacement is the same as the existing value.

PyTuple_SET_ITEM() does not exhibit this problem as it abandons values rather than discarding them.

For code and tests see:

  • C: in src/cpy/Containers/DebugContainers.c:
    • dbg_PyTuple_SetItem_steals_replace

    • dbg_PyTuple_SetItem_replace_with_same

  • CPython: in src/cpy/RefCount/cRefCount.c:
    • test_PyTuple_SetItem_steals_replace

    • test_PyTuple_SetItem_replace_same

  • Python: in tests.unit.test_c_ref_count
    • test_PyTuple_SetItem_steals_replace()

    • test_PyTuple_SetItem_replace_same()

4.3.1.3. PyTuple_SetItem() Failures

PyTuple_SetItem() can return a non-zero error code for these reasons:

  • The given container is not a tuple.

  • The index is out of range; index < 0 or index >= tuple length (negative indexes are not allowed).

Warning

A consequence of failure is that the value being inserted will be decref’d. For example this code will segfault:

PyObject *container = PyTuple_New(1); /* Reference count will be 1. */
PyObject *value = new_unique_string(__FUNCTION__, NULL); /* Ref count will be 1. */
PyTuple_SetItem(container, 1, value); /* Index out of range. */
Py_DECREF(value); /* value has already been decref'd and free'd so this will SIGSEGV */

This is not described in the Python documentation.

For code tests see, when the container is not a tuple:

  • C: dbg_PyTuple_SetItem_fails_not_a_tuple in src/cpy/Containers/DebugContainers.c.

  • CPython: test_PyTuple_SetItem_fails_not_a_tuple in src/cpy/RefCount/cRefCount.c.

  • Python: tests.unit.test_c_ref_count.test_PyTuple_SetItem_fails_not_a_tuple.

And, when the index out of range:

  • C: dbg_PyTuple_SetItem_fails_out_of_range in src/cpy/Containers/DebugContainers.c.

  • CPython: test_PyTuple_SetItem_fails_out_of_range in src/cpy/RefCount/cRefCount.c.

  • Python: tests.unit.test_c_ref_count.test_PyTuple_SetItem_fails_out_of_range.

Note

I’m not really sure why the PyTuple_SetItem() API exists. Tuples are meant to be immutable but this API treats existing tuples as mutable. It would seem like PyTuple_SET_ITEM() would be enough.

4.3.2. PyTuple_SET_ITEM()

PyTuple_SET_ITEM() is a function like macro that inserts an object into a tuple without any error checking (see PyTuple_SET_ITEM() Failures below). However type checking is performed as an assertion if Python is built in debug mode or with assertions. Because of the absence of checks, it is slightly faster than PyTuple_SetItem() . This is usually used on newly created tuples.

Importantly PyTuple_SET_ITEM() behaves differently to PyTuple_SetItem() when replacing another object.

4.3.2.1. PyTuple_SET_ITEM() Basic Usage

PyTuple_SET_ITEM() steals a reference just like PyTuple_SetItem().

PyObject *container = PyTuple_New(1); /* Reference count will be 1. */
PyObject *value = new_unique_string(__FUNCTION__, NULL); /* Ref count will be 1. */
PyTuple_SET_ITEM(container, 0, value); /* Ref count of value will be 1. */
/* get_item == value and Ref count will be 1. */
PyObject *get_item = PyTuple_GET_ITEM(container, 0);
assert(get_item == value && Py_REFCNT(value) == 1);
Py_DECREF(container); /* The contents of the container, value, will be decref'd */
/* Do not do this as the container deals with this. */
/* Py_DECREF(value); */

For code and tests see:

  • C: in src/cpy/Containers/DebugContainers.c:
    • dbg_PyTuple_PyTuple_SET_ITEM_steals()

  • CPython: in src/cpy/RefCount/cRefCount.c:
    • test_PyTuple_PyTuple_SET_ITEM_steals()

  • Python: in tests.unit.test_c_ref_count
    • test_PyTuple_PyTuple_SET_ITEM_steals()

4.3.2.2. PyTuple_SET_ITEM() Replacement

PyTuple_SET_ITEM() differs from PyTuple_SetItem() when replacing an existing element in a tuple as the original reference will be leaked. This is because PyTuple_SET_ITEM() abandons the previous reference (see Abandoned References):

PyObject *container = PyTuple_New(1); /* Reference count will be 1. */
PyObject *value_a = new_unique_string(__FUNCTION__, NULL); /* Ref count will be 1. */
PyTuple_SET_ITEM(container, 0, value_a); /* Ref count of value_a will be 1. */
PyObject *value_b = new_unique_string(__FUNCTION__, NULL); /* Ref count will be 1. */
PyTuple_SET_ITEM(container, 0, value_b);
assert(Py_REFCNT(value_a) == 1);
/* Ref count of value_b will be 1,
 * value_a ref count will still be at 1 and value_a will be leaked unless decref'd. */

Note

Because PyTuple_SET_ITEM() abandons the previous reference it does not have the problem with undefined behaviour that PyTuple_Set_Item() has. For that see the warning about undefined behaviour in PyTuple_Set_Item() PyTuple_SetItem() Replacement.

For code and tests see:

  • C: in src/cpy/Containers/DebugContainers.c:
    • dbg_PyTuple_SET_ITEM_steals_replace()

    • dbg_PyTuple_SET_ITEM_replace_with_same()

  • CPython: in src/cpy/RefCount/cRefCount.c:
    • test_PyTuple_SetItem_steals_replace()

    • test_PyTuple_SET_ITEM_replace_same()

  • Python: in tests/unit/test_c_ref_count.py:
    • test_PyTuple_SetItem_steals_replace

    • test_PyTuple_SET_ITEM_replace_same.

4.3.2.3. PyTuple_SET_ITEM() Failures

PyTuple_SET_ITEM() minimises the error checking that PyTuple_SetItem() does, so:

  • It does not check if the given container is a Tuple.

  • It does not check if the index in range.

If either of those is wrong then PyTuple_SET_ITEM() is capable of writing to arbitrary memory locations, and the result is likely to be tragic, mostly undefined behaviour and/or memory corruption.

4.3.3. Setting and Replacing NULL

This looks at what happens when setting or replacing a NULL pointer in a tuple. Both PyTuple_SetItem() and PyTuple_SET_ITEM() behave the same way.

4.3.3.1. Setting NULL

Setting a NULL will not cause an error:

PyObject *container = PyTuple_New(1);
assert(!PyErr_Occurred());
PyTuple_SetItem(container, 0, NULL);
assert(!PyErr_Occurred());

For code and tests see:

  • C: in src/cpy/Containers/DebugContainers.c:
    • dbg_PyTuple_SetIem_NULL()

  • CPython: in src/cpy/RefCount/cRefCount.c:
    • test_PyTuple_SetItem_NULL()

  • Python: in tests/unit/test_c_ref_count.py
    • test_PyTuple_SetItem_NULL().

And:

PyObject *container = PyTuple_New(1);
assert(!PyErr_Occurred());
PyTuple_SET_ITEM(container, 0, NULL);
assert(!PyErr_Occurred());

For code and tests see:

  • C: in src/cpy/Containers/DebugContainers.c:
    • dbg_PyTuple_SET_ITEM_NULL()

  • CPython: in src/cpy/RefCount/cRefCount.c:
    • test_PyTuple_SET_ITEM_NULL()

  • Python: in tests/unit/test_c_ref_count.py
    • test_PyTuple_SET_ITEM_NULL().

4.3.3.2. Replacing NULL

Replacing a NULL will not cause an error, the original value is abandoned (see Abandoned References) and the replaced value reference is stolen (see “Stolen” References):

PyObject *container = PyTuple_New(1);
PyTuple_SetItem(container, 0, NULL);
PyObject *value = new_unique_string(__FUNCTION__, NULL); /* Ref Count of value is 1. */
PyTuple_SetItem(container, 0, value); /* Ref Count of value is still 1. */

For code and tests see:

  • C: in src/cpy/Containers/DebugContainers.c:
    • dbg_PyTuple_SetIem_NULL_SetIem

  • CPython: in src/cpy/RefCount/cRefCount.c:
    • test_PyTuple_SetItem_NULL_SetIem

  • Python: in tests/unit/test_c_ref_count.py:
    • test_PyTuple_SetItem_NULL_SetIem().

And:

PyObject *container = PyTuple_New(1);
PyTuple_SET_ITEM(container, 0, NULL);
PyObject *value = new_unique_string(__FUNCTION__, NULL); /* Ref Count of value is 1. */
PyTuple_SET_ITEM(container, 0, value); /* Ref Count of value is still 1. */

For code and tests see:

  • C: in src/cpy/Containers/DebugContainers.c:
    • dbg_PyTuple_SET_ITEM_NULL_SET_ITEM()

  • CPython: in src/cpy/RefCount/cRefCount.c:
    • test_PyTuple_SET_ITEM_NULL_SET_ITEM()

  • Python: in tests/unit/test_c_ref_count.py:
    • test_PyTuple_SET_ITEM_NULL_SET_ITEM().

4.3.4. PyTuple_Pack()

PyTuple_Pack() takes a length and a variable argument list of PyObjects. Each of those PyObjects reference counts will be incremented. In that sense it behaves as Py_BuildValue().

Note

PyTuple_Pack() is implemented as a separate low level routine, it does not invoke PyTuple_SetItem() or PyTuple_SET_ITEM() .

For example:

PyObject *value_a = new_unique_string(__FUNCTION__, NULL);
PyObject *value_b = new_unique_string(__FUNCTION__, NULL);
PyObject *container = PyTuple_Pack(2, value_a, value_b);
assert(Py_REFCNT(value_a) == 2);
assert(Py_REFCNT(value_b) == 2);

Py_DECREF(container);

/* Leaks: */
assert(Py_REFCNT(value_a) == 1);
assert(Py_REFCNT(value_b) == 1);
/* Fix leaks: */
Py_DECREF(value_a);
Py_DECREF(value_b);

For code and tests see:

  • C: in src/cpy/Containers/DebugContainers.c:
    • dbg_PyTuple_PyTuple_Pack

  • CPython: in src/cpy/RefCount/cRefCount.c:
    • test_PyTuple_Py_PyTuple_Pack

  • Python: in tests/unit/test_c_ref_count.py:
    • test_PyTuple_Py_PyTuple_Pack().

4.3.5. Py_BuildValue()

Py_BuildValue() is a very convenient way to create tuples, lists and dictionaries. Py_BuildValue("(O)", value); will increment the refcount of value and this can, potentially, leak:

PyObject *value = new_unique_string(__FUNCTION__, NULL);
/* value reference count is 1. */
PyObject *container = Py_BuildValue("(O)", value);
/* value reference count is incremented to 2. */
assert(Py_REFCNT(value) == 2);

Py_DECREF(container);
/* value reference count is decremented to 1. */
assert(Py_REFCNT(value_a) == 1);

/* value is leaked if Py_DECREF(value) is not called. */
/* Fix leak. */
Py_DECREF(value);

For code and tests see:

  • C: in src/cpy/Containers/DebugContainers.c:
    • dbg_PyTuple_Py_BuildValue()

  • CPython: in src/cpy/RefCount/cRefCount.c:
    • test_PyTuple_Py_BuildValue

  • Python: in tests/unit/test_c_ref_count.py:
    • test_PyTuple_Py_BuildValue().

4.3.6. Tuple Getters

There are these APIs for getting an item from a tuple:

  • PyTuple_GetItem(), it returns a borrowed reference and will error if the supplied container is not tuple or the index is negative or out of range.

  • PyTuple_GET_ITEM(), it returns a borrowed reference and there is no error checking for the container being a tuple or the index being in range. The type checking is performed as an assertion if Python is built in debug mode or with assertions. If not the results are undefined.

4.3.7. Summary

4.4. Lists

4.4.1. PyList_SetItem() and PyList_SET_ITEM()

PyList_SetItem() and PyList_SET_ITEM() behave identically to their equivalents PyTuple_SetItem() (link PyTuple_SetItem()) and PyTuple_SET_ITEM() (link PyTuple_SET_ITEM()).

Note that, as with tuples, PyList_SetItem() and PyList_SET_ITEM() behave differently on replacement of values (see PyTuple_SET_ITEM() Replacement). The Python documentation on PyList_SET_ITEM() correctly identifies when a leak can occur (unlike PyTuple_SET_ITEM()).

On replacement with PyList_SetItem() heed the warning in PyTuple_SetItem() Replacement as PyList_SetItem() holds the same danger.

Py_BuildValue() also behaves identically, as far as reference counts are concerned, with Lists as it does with Tuples (see Py_BuildValue()).

4.4.2. PyList_Append()

PyList_Append() (a C function) adds an object onto the end of a list with error checking. This increments the reference count of the given value which will be decremented on container destruction. For example:

PyObject *container = PyList_New(0);
PyObject *value = new_unique_string(__FUNCTION__, NULL);
PyList_Append(container, value);
assert(Py_REFCNT(value) == 2);
Py_DECREF(container);
/* A leak unless decref'd. */
assert(Py_REFCNT(value) == 1);

PyList_Append() uses PyList_SET_ITEM() in its implementation. PyList_Append() can fail for two reasons:

  • The given container is not a list.

  • The given value is NULL.

On failure the reference count of value is unchanged and a SystemError is raised with the text “bad argument to internal function”.

For code and tests, including failure modes, see:

  • C: dbg_PyList_Append... in src/cpy/Containers/DebugContainers.c.

  • CPython: test_PyList_Append... in src/cpy/RefCount/cRefCount.c.

  • Python: tests.unit.test_c_ref_count.test_PyList_Append etc.

4.4.3. PyList_Insert()

PyList_Insert() (a C function) inserts an object before a specific index in a list with error checking. This increments the reference count of the given value which will be decremented on container destruction.

PyList_Insert() is equivalent to list.insert(...), for example:

>>> l = []
>>> l.insert(123, "Hello")
>>> l.insert(-123, "World")
>>> l
['World', 'Hello']

PyList_Insert() can fail for two reasons:

  • The given container is not a list.

  • The given value is NULL.

Note

PyList_Insert() does not fail because of any value of the index, either positive or negative (this is not identified in the Python documentation).

On failure the reference count of value is unchanged, PyList_Insert() returns -1, and a SystemError is set with the text “bad argument to internal function”.

For code and tests, including failure modes, see:

  • C: dbg_PyList_Insert... in src/cpy/Containers/DebugContainers.c.

  • CPython: test_PyList_Insert... in src/cpy/RefCount/cRefCount.c.

  • Python: tests.unit.test_c_ref_count.test_PyList_Insert etc.

Note

The Python documentation does not mention (but implies) that if the index is greater than the list length then the value is appended to the list.

For example (dbg_PyList_Insert_Is_Truncated() in src/cpy/Containers/DebugContainers.c):

PyObject *container = PyList_New(0);
PyObject *value = new_unique_string(__FUNCTION__, NULL);
// Insert before index 4
if (PyList_Insert(container, 4L, value)) {
    assert(0);
}
assert(Py_REFCNT(value) == 2);
PyObject *get_item;
// PyList_Insert at 4 actually inserts at 0.
assert(PyList_GET_SIZE(container) == 1L);
get_item = PyList_GET_ITEM(container, 0L);
assert(get_item == value);

Note

Neither the Python documentation for PyList_Insert() or list.insert() does not make this clear that index can be negative in which case the index is calculated from the end. If that index calculation is less than zero it is truncated to zero.

For example (dbg_PyList_Insert_Negative_Index() in src/cpy/Containers/DebugContainers.c):

PyObject *container = PyList_New(0);
PyObject *value = new_unique_string(__FUNCTION__, NULL);
// Insert at end
if (PyList_Insert(container, -1L, value)) {
    assert(0);
}
assert(Py_REFCNT(value) == 2);
PyObject *get_item;
// PyList_Insert at -1 actually inserts at 0.
assert(PyList_GET_SIZE(container) == 1L);
get_item = PyList_GET_ITEM(container, 0L);
assert(get_item == value);

4.4.4. Py_BuildValue()

As with tuples Py_BuildValue() is a very convenient way to create lists. Py_BuildValue("[O]", value); will increment the refcount of value and this can, potentially, leak.

4.4.5. List Getters

There are these APIS for getting an item from a list:

4.4.6. Summary

4.5. Dictionaries

This section describes how reference counts are affected when building and accessing dictionaries.

4.5.1. PyDict_SetItem()

The Python documentation for PyDict_SetItem() is incomplete. PyDict_SetItem() changes the key and value reference counts according to these rules:

  • If the key exists in the dictionary then key’s reference count remains the same.

  • If the key does not exist in the dictionary then its reference count will be incremented.

  • The value’s reference count will always be incremented.

  • If the key exists in the dictionary then the previous value reference count will be decremented before the value is replaced by the new value (and the new value reference count is incremented). See Discarded References. If the key exists in the dictionary and the value is the same then this means, effectively, that reference counts of both key and value remain unchanged.

Warning

If either the key or the value are NULL this will segfault. See dbg_PyDict_SetItem_NULL_key() and dbg_PyDict_SetItem_NULL_value() in src/cpy/Containers/DebugContainers.c.

This code illustrates PyDict_SetItem() with assert() showing the reference count:

PyObject *container = PyDict_New();
PyObject *key = new_unique_string(__FUNCTION__, NULL);
PyObject *value_a = new_unique_string(__FUNCTION__, NULL);
assert(Py_REFCNT(key) == 1);
assert(Py_REFCNT(value_a) == 1);
/* Insert a new key value. */
if (PyDict_SetItem(container, key, value_a)) {
    assert(0);
}
assert(Py_REFCNT(key) == 2);
assert(Py_REFCNT(value_a) == 2);

Now replace the value with another value:

/* Replace a value for the key. */
PyObject *value_b = new_unique_string(__FUNCTION__, NULL);
assert(Py_REFCNT(key) == 2);
assert(Py_REFCNT(value_a) == 2);
assert(Py_REFCNT(value_b) == 1);
if (PyDict_SetItem(container, key, value_b)) {
    assert(0);
}
assert(Py_REFCNT(key) == 2);
assert(Py_REFCNT(value_a) == 1);
assert(Py_REFCNT(value_b) == 2);

Now replace the value with the same value, reference counts remain the same:

/* Replace with the same value for the key. */
if (PyDict_SetItem(container, key, value_b)) {
    assert(0);
}
assert(Py_REFCNT(key) == 2);
assert(Py_REFCNT(value_a) == 1);
assert(Py_REFCNT(value_b) == 2);

4.5.1.1. PyDict_SetItem() Failure

PyDict_SetItem() can fail for the following reasons:

  • The container is not a dictionary (or a sub-class of a dictionary, see PyDict_Check()).

  • The key is not hashable (PyObject_Hash() returns -1).

  • If either the key or the value is NULL this will cause a SIGSEGV (or some other disaster). These are checked with asserts if Python is built in debug mode or with assertions.

For code and tests see:

  • C: in src/cpy/Containers/DebugContainers.c:
    • dbg_PyDict_SetItem_*()

  • CPython: in src/cpy/RefCount/cRefCount.c:
    • test_PyDict_SetItem_*()

  • Python: in tests/unit/test_c_ref_count.py:
    • test_PyDict_SetItem_increments()

Note

In src/cpy/Containers/DebugContainers.c there are failure tests that cause a SIGSEGV if ACCEPT_SIGSEGV is non zero. ACCEPT_SIGSEGV is defined in src/cpy/Containers/DebugContainers.h.

4.5.2. PyDict_SetDefault()

PyDict_SetDefault() is equivalent to the Python method dict.setdefault() in Python. The C function signature is:

PyObject *PyDict_SetDefault(PyObject *p, PyObject *key, PyObject *defaultobj);

The idea is that if the key exists then the appropriate value is returned and the default value is unused. If the key does not exist then the default value is inserted into the dictionary and returned.

4.5.2.1. If the Default Value is Unused

If the key already exists in the dictionary the reference counts of the key, existing value and default value are unchanged so the return value is a borrowed reference (see “Borrowed” References).

4.5.2.2. If the Default Value is Used

If the key does not exist in the dictionary the reference counts of the key and default value are incremented.

These reference count changes are not particularly clear from the official Python documentation.

For code and tests see:

  • C, in src/cpy/Containers/DebugContainers.c:
    • dbg_PyDict_SetDefault_default_unused()

    • dbg_PyDict_SetDefault_default_used()

  • CPython, in src/cpy/RefCount/cRefCount.c.

    test_PyDict_SetDefault_default_unused() test_PyDict_SetDefault_default_used()

  • Python, pytest, in tests.unit.test_c_ref_count:
    • test_PyDict_SetDefault_default_unused()

    • test_PyDict_SetDefault_default_used()

4.5.3. PyDict_SetDefaultRef() [Python 3.13+]

PyDict_SetDefaultRef() sets a default value and retrieves the actual value. This is new in Python 3.13+. The C function signature is:

int PyDict_SetDefaultRef(
    PyObject *dictionary, PyObject *key, PyObject *default_value, PyObject **result
);

4.5.3.1. *result

Any previous *result is always abandoned (see Abandoned References). To emphasise, there is no decrementing the reference count of the existing value (if any). This is important as the following code snippet shows:

PyObject *result; /* Refers to an arbitrary memory location. */
/* Now if PyDict_SetDefaultRef() were to attempt to Py_DECREF(result)
 * the results will be undefined.
*/
PyDict_SetDefaultRef(container, key, default_value, &result);

4.5.3.2. Key Exists

If the key already exists in the dictionary PyDict_SetDefaultRef() returns 1. The reference counts are changed as follows:

  • key: unchanged.

  • value: incremented by one

  • default_value: unchanged.

*result is equal to the stored value.

For example:

 1PyObject *container = PyDict_New();
 2PyObject *key = new_unique_string(__FUNCTION__, NULL);
 3PyObject *val = new_unique_string(__FUNCTION__, NULL);
 4/* At this point the reference counts are:
 5 * key: 1
 6 * val: 1
 7 */
 8// Set the key/value
 9PyDict_SetItem(container, key, val);
10/* At this point the reference counts are:
11 * key: 2
12 * val: 2
13 */
14// Create a default value and a result.
15PyObject *default_value = new_unique_string(__FUNCTION__, NULL);
16PyObject *result = NULL;
17/* At this point the reference counts are:
18 * default_value: 1
19 * result: N/A
20 */
21PyDict_SetDefaultRef(container, key, default_value, &result);
22/* Now the reference counts are:
23 * key: 2
24 * val: 3
25 * default_value: 1
26 * result: 3 as it equals val.
27 */
28Py_DECREF(container);
29/* Now the reference counts are:
30 * key: 1
31 * val: 2
32 * default_value: 1
33 * result: 2 as it equals val.
34 */

For code and tests see:

  • C, in src/cpy/Containers/DebugContainers.c:
    • dbg_PyDict_SetDefaultRef_default_unused()

  • CPython, in src/cpy/RefCount/cRefCount.c.

    test_PyDict_SetDefaultRef_default_unused()

  • Python, pytest, in tests.unit.test_c_ref_count:
    • test_PyDict_SetDefaultRef_default_unused()

4.5.3.3. Key Does not Exist

If the key does not exists in the dictionary PyDict_SetDefaultRef() returns 0. The reference counts are changed as follows:

  • key: incremented by one.

  • default_value: incremented by two. The rationale is one increment as the default_value is inserted into the dictionary then a second increment as the default_value is ‘returned’ as *result.

*result is equal to the default_value.

For example:

 1PyObject *container = PyDict_New();
 2PyObject *key = new_unique_string(__FUNCTION__, NULL);
 3// Create a default value and a result.
 4PyObject *default_value = new_unique_string(__FUNCTION__, NULL);
 5PyObject *result = NULL;
 6/* At this point the reference counts are:
 7 * key: 1
 8 * default_value: 1
 9 * result: N/A
10 */
11PyDict_SetDefaultRef(container, key, default_value, &result);
12/* Now the reference counts are:
13 * key: 2
14 * default_value: 3
15 * result: 3 as it equals default_value.
16 */
17Py_DECREF(container);
18/* Now the reference counts are:
19 * key: 1
20 * default_value: 2
21 * result: 2 as it equals default_value.
22 */

These reference count changes are not particularly clear from the official Python documentation.

For code and tests see:

  • C, in src/cpy/Containers/DebugContainers.c:
    • dbg_PyDict_SetDefaultRef_default_used()

  • CPython, in src/cpy/RefCount/cRefCount.c.

    test_PyDict_SetDefaultRef_default_used()

  • Python, pytest, in tests.unit.test_c_ref_count:
    • test_PyDict_SetDefaultRef_default_used()

4.5.3.4. Failure

Todo

PyDict_SetDefaultRef() failure modes.

4.5.4. PyDict_GetItem()

PyDict_GetItem() returns a borrowed reference (“Borrowed” References) to an existing value or NULL if the key does not exist in the dictionary.

Warning

If the key is NULL this will segfault. See dbg_PyDict_GetItem_key_NULL() in src/cpy/Containers/DebugContainers.c.

4.5.5. PyDict_GetItemRef() [Python 3.13+]

PyDict_GetItemRef() gets a new strong reference to a value from a dictionary.

The C signature is:

int PyDict_GetItemRef(PyObject *p, PyObject *key, PyObject **result);

4.5.5.1. Key is Present

If the key is in the dictionary then increment the reference count of the value and set *result to the value. The reference count of the key is unchanged. The function returns 1.

For code and tests see:

  • C, in src/cpy/Containers/DebugContainers.c:
    • dbg_PyDict_GetItemRef()

  • CPython, in src/cpy/RefCount/cRefCount.c.

    test_PyDict_SetDefaultRef_default_used()

  • Python, pytest, in tests.unit.test_c_ref_count:
    • test_PyDict_SetDefaultRef_default_used()

4.5.5.2. Failure

Todo

PyDict_GetItemRef() failure modes.

4.5.6. PyDict_Pop() [Python 3.13+]

PyDict_Pop() removes a specific value. This is new in Python 3.13+. The C function signature is:

int int PyDict_Pop(PyObject *p, PyObject *key, PyObject **result);

4.5.6.1. *result

Any previous *result is always abandoned (see Abandoned References). To emphasise, there is no decrementing the reference count of the existing value (if any). This is important as the following code snippet shows:

PyObject *result; /* Refers to an arbitrary memory location. */
/* Now if PyDict_Pop() were to attempt to Py_DECREF(result)
 * the results will be undefined.
*/
PyDict_Pop(container, key, &result);

4.5.6.2. Key Exists

If the key already exists in the dictionary PyDict_Pop() returns 1. The reference counts are changed as follows:

  • key: decremented by one

  • value: unchanged.

*result is equal to the stored value.

For example:

 1PyObject *container = PyDict_New();
 2PyObject *key = new_unique_string(__FUNCTION__, NULL);
 3PyObject *val = new_unique_string(__FUNCTION__, NULL);
 4/* At this point the reference counts are:
 5 * key: 1
 6 * val: 1
 7 */
 8// Set the key/value
 9PyDict_SetItem(container, key, val);
10/* At this point the reference counts are:
11 * key: 2
12 * val: 2
13 */
14PyObject *result;
15PyDict_Pop(container, key, &result);
16/* Now the reference counts are:
17 * key: 1
18 * val: 2
19 * result: 2 as it equals val.
20 */

For code and tests see:

  • C, in src/cpy/Containers/DebugContainers.c:
    • dbg_PyDict_Pop_key_present()

  • CPython, in src/cpy/RefCount/cRefCount.c.

    test_PyDict_Pop_key_present()

  • Python, pytest, in tests.unit.test_c_ref_count:
    • test_PyDict_Pop_key_present()

4.5.6.3. Key Does not Exist

If the key does not exists in the dictionary PyDict_Pop() returns 0. The reference counts are changed as follows:

  • key: unchanged.

*result is set to NULL, any previous value is abandoned (see Abandoned References).

For example:

PyObject *container = PyDict_New();
PyObject *key = new_unique_string(__FUNCTION__, NULL);
// Create a default value and a result.
PyObject *dummy_value = new_unique_string(__FUNCTION__, NULL);
PyObject *result = dummy_value;
/* At this point the reference counts are:
 * key: 1
 * dummy_value: 1
 * result: 1 as it is equal to dummy_value.
 */
PyDict_Pop(container, key, &result);
/* Now the reference counts are:
 * key: 1
 * dummy_value: 1
 * result: is NULL.
 */
Py_DECREF(container);
/* No change in the reference counts. */

For code and tests see:

  • C, in src/cpy/Containers/DebugContainers.c:
    • dbg_PyDict_Pop_key_absent()

  • CPython, in src/cpy/RefCount/cRefCount.c.

    test_PyDict_Pop_key_absent()

  • Python, pytest, in tests.unit.test_c_ref_count:
    • test_PyDict_Pop_key_absent()

4.5.6.4. Failure

Todo

Finish Dictionary PyDict_Pop() Failure

4.5.7. Other APIs

This section describes other dictionary APIs that are simple to describe and have no complications.

Note

There are no tests for many of these APIs in the current version of this project.

Todo

Finish Dictionary “Other APIs”

4.5.7.1. PyDict_GetItemWithError()

PyDict_GetItemWithError() gets a new borrowed reference to a value from a dictionary or NULL. Unlike PyDict_GetItem() this will set an exception if appropriate.

The C signature is:

PyObject *PyDict_GetItemWithError(PyObject *p, PyObject *key);

Currently, the only failure mode is if the first argument is not a dictionary.

For code and tests see:

  • C, in src/cpy/Containers/DebugContainers.c:
    • dbg_PyDict_GetItemWithError_fails()

4.5.7.2. PyDict_DelItem()

PyDict_DelItem() removes a specific value if it exists. The reference count of the value will be decremented. The key must be hashable; if it isn’t a TypeError is set. If key is not in the dictionary a KeyError is set. Returns 0 on success or -1 on failure in which case an exception will have been set.

The C function signature is:

int PyDict_DelItem(PyObject *p, PyObject *key);

Todo

Complete PyDict_DelItem() with code examples.

4.5.7.3. PyDict_Items()

PyDict_Items() returns a new Python list containing new tuples of (key, value). Each key and value will have their reference count incremented. That is to say calling Py_DECREF on the result will change all the reference counts within the dictionary to their previous values.

The C function signature is:

Pyobject *PyDict_Items(PyObject *p);

Todo

Complete PyDict_Items() with code examples.

4.5.7.4. PyDict_Keys()

PyDict_Keys() returns a new Python list containing all the keys. Each key will have its reference count incremented. That is to say calling Py_DECREF on the result will change all the reference counts within the dictionary to their previous values.

The C function signature is:

Pyobject *PyDict_Keys(PyObject *p);

Todo

Complete PyDict_Keys() with code examples.

4.5.7.5. PyDict_Values()

PyDict_Values() returns a new Python list containing all the values. Each value will have its reference count incremented. That is to say calling Py_DECREF on the result will change all the reference counts within the dictionary to their previous values.

The C function signature is:

Pyobject *PyDict_Values(PyObject *p);

Todo

Complete PyDict_Values() with code examples.

4.5.7.6. PyDict_Next()

PyDict_Next() is the standard way of iterating through all the keys and values. Each key and value will is a borrowed reference. The C function signature is:

int PyDict_Next(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue);

Todo

Complete PyDict_Next() with code examples.

4.5.7.7. Py_BuildValue()

Py_BuildValue() is a very convenient way to create dictionaries. Py_BuildValue("{OO}", key, value); will increment the refcount of the key and value and this can, potentially, leak.

4.6. Sets

The set API is simple with no real difficulties for the user.

4.6.1. PySet_Add()

PySet_Add() is fairly straightforward. The set will increment the reference count of the value if it is not already in the set.

This returns 0 on success or -1 on failure in which case an exception will have been set which will be:

  • A SystemError if set is not an instance of set or its subtype.

  • A TypeError if the key is unhashable.

  • A MemoryError if there is no room to grow.

Here is an example:

PyObject *container = PySet_New(NULL);
/* Py_REFCNT(container) is 1 */
PyObject *value = new_unique_string(__FUNCTION__, NULL);
/* Py_REFCNT(value) is 1 */
int ret_val = PySet_Add(container, value);
assert(ret_val == 0);
/* Py_REFCNT(value) is now 2 */

/* Clean up. */
Py_DECREF(container);
/* Py_REFCNT(value) is now 1 */
Py_DECREF(value);

When adding something that already exists in the set does not increment the reference count:

PyObject *container = PySet_New(NULL);
/* Py_REFCNT(container) is 1 */
PyObject *value = new_unique_string(__FUNCTION__, NULL);
/* Py_REFCNT(value) is 1 */
int ret_val = PySet_Add(container, value);
assert(ret_val == 0);
/* Py_REFCNT(value) is now 2 */

/* Add duplicate. */
ret_val = PySet_Add(container, value);
assert(ret_val == 0);
/* Py_REFCNT(value) is still 2 */

/* Clean up. */
Py_DECREF(container);
/* Py_REFCNT(value) is now 1 */
Py_DECREF(value);

4.6.2. PySet_Discard()

PySet_Discard() is also fairly straightforward. The set will discard (Discarded References) the value thus:

PyObject *container = PySet_New(NULL);
/* Py_REFCNT(container) is 1 */
PyObject *value = new_unique_string(__FUNCTION__, NULL);
/* Py_REFCNT(value) is 1 */
int ret_val = PySet_Add(container, value);
assert(ret_val == 0);
/* Py_REFCNT(value) is now 2 */

/* Discard. */
ret_val = PySet_Discard(container, value);
assert(ret_val == 1);
/* Py_REFCNT(value) is now 1 */

/* Clean up. */
Py_DECREF(container);
/* Py_REFCNT(value) is still 1 */
Py_DECREF(value);

4.6.3. PySet_Pop()

PySet_Pop() will return a new reference to the existing object and it is up to caller to decrement the reference count appropriately.

For example, the reference counts work as follows:

PyObject *container = PySet_New(NULL);
/* Py_REFCNT(container) is 1 */
PyObject *value = new_unique_string(__FUNCTION__, NULL);
/* Py_REFCNT(value) is 1 */
int ret_val = PySet_Add(container, value);
assert(ret_val == 0);
/* Py_REFCNT(value) is now 2 */

/* Pop. */
PyObject *popped_value = PySet_Pop(container);
assert(popped_value == value);
/* Py_REFCNT(value) is still 2 */

/* Clean up. */
Py_DECREF(container);
/* Py_REFCNT(value) is still 2 so need to double Py_DECREF calls. */
Py_DECREF(value);
Py_DECREF(value);

So this is how PySet_Pop() might be used in practice:

 1void add_to_set(PyObject *container) {
 2    PyObject *value = new_unique_string(__FUNCTION__, NULL);
 3    /* Py_REFCNT(value) is 1 */
 4    int ret_val = PySet_Add(container, value);
 5    assert(ret_val == 0);
 6    /* Py_REFCNT(value) is now 2 */
 7    /* Decrement our local value */
 8    Py_DECREF(value);
 9    /* Now the container has the only reference to the value. */
10}
11
12void pop_from_set(PyObject *container) {
13    PyObject *value = PySet_Pop(container);
14    /* Do something with the value... */
15
16    /* Then as we 'own' value we need to free it. */
17    Py_DECREF(value);
18}
19
20PyObject *container = PySet_New(NULL);
21add_to_set(container);
22pop_from_set(container);
23/* Clean up. */
24Py_DECREF(container);

4.7. Summary

This summarises where the Python documentation is wrong, absent or misleading and where you might get into trouble.

4.7.1. Tuples

4.7.2. Lists

4.7.3. Dictionaries

Todo

Complete the summary of dictionary APIs and their documentation lacunae.

4.7.4. Sets

The set API is much cleaner than the others and contains few gotchas. In summary:

  • PySet_Add() will increment the reference count of the value if it is not already in the set. See PySet_Add().

  • PySet_Discard() will decrement the reference count of the value and returns it. It is up to the caller to decrement the reference count of the returned value. See PySet_Discard().

  • PySet_Pop() does not decrement the reference count of the returned value, it is abandoned (see Abandoned References). It is up to the caller to decrement the reference count of the returned value. See PySet_Pop().

Footnotes