gh-112066: Add `PyDict_SetDefaultRef` function. by colesbury · Pull Request #112123 · python/cpython · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions Doc/c-api/dict.rst
6 changes: 6 additions & 0 deletions Doc/whatsnew/3.13.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1440,6 +1440,12 @@ New Features
not needed.
(Contributed by Victor Stinner in :gh:`106004`.)

* Added :c:func:`PyDict_SetDefaultRef`, which is similar to
:c:func:`PyDict_SetDefault` but returns a :term:`strong reference` instead of
a :term:`borrowed reference`. This function returns ``-1`` on error, ``0`` on
insertion, and ``1`` if the key was already present in the dictionary.
(Contributed by Sam Gross in :gh:`112066`.)

* Add :c:func:`PyDict_ContainsString` function: same as
:c:func:`PyDict_Contains`, but *key* is specified as a :c:expr:`const char*`
UTF-8 encoded bytes string, rather than a :c:expr:`PyObject*`.
Expand Down
10 changes: 10 additions & 0 deletions Include/cpython/dictobject.h
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,16 @@ PyAPI_FUNC(PyObject *) _PyDict_GetItemStringWithError(PyObject *, const char *);
PyAPI_FUNC(PyObject *) PyDict_SetDefault(
PyObject *mp, PyObject *key, PyObject *defaultobj);

// Inserts `key` with a value `default_value`, if `key` is not already present
// in the dictionary. If `result` is not NULL, then the value associated
// with `key` is returned in `*result` (either the existing value, or the now
// inserted `default_value`).
// Returns:
// -1 on error
// 0 if `key` was not present and `default_value` was inserted
// 1 if `key` was present and `default_value` was not inserted
PyAPI_FUNC(int) PyDict_SetDefaultRef(PyObject *mp, PyObject *key, PyObject *default_value, PyObject **result);

/* Get the number of items of a dictionary. */
static inline Py_ssize_t PyDict_GET_SIZE(PyObject *op) {
PyDictObject *mp;
Expand Down
22 changes: 22 additions & 0 deletions Lib/test/test_capi/test_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,28 @@ def test_dict_setdefault(self):
# CRASHES setdefault({}, 'a', NULL)
# CRASHES setdefault(NULL, 'a', 5)

def test_dict_setdefaultref(self):
setdefault = _testcapi.dict_setdefaultref
dct = {}
self.assertEqual(setdefault(dct, 'a', 5), 5)
self.assertEqual(dct, {'a': 5})
self.assertEqual(setdefault(dct, 'a', 8), 5)
self.assertEqual(dct, {'a': 5})

dct2 = DictSubclass()
self.assertEqual(setdefault(dct2, 'a', 5), 5)
self.assertEqual(dct2, {'a': 5})
self.assertEqual(setdefault(dct2, 'a', 8), 5)
self.assertEqual(dct2, {'a': 5})

self.assertRaises(TypeError, setdefault, {}, [], 5) # unhashable
self.assertRaises(SystemError, setdefault, UserDict(), 'a', 5)
self.assertRaises(SystemError, setdefault, [1], 0, 5)
self.assertRaises(SystemError, setdefault, 42, 'a', 5)
# CRASHES setdefault({}, NULL, 5)
# CRASHES setdefault({}, 'a', NULL)
# CRASHES setdefault(NULL, 'a', 5)

def test_mapping_keys_valuesitems(self):
class BadMapping(dict):
def keys(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Add :c:func:`PyDict_SetDefaultRef`: insert a key and value into a dictionary
if the key is not already present. This is similar to
:meth:`dict.setdefault`, but returns an integer value indicating if the key
was already present. It is also similar to :c:func:`PyDict_SetDefault`, but
returns a strong reference instead of a borrowed reference.
26 changes: 26 additions & 0 deletions Modules/_testcapi/dict.c
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,31 @@ dict_setdefault(PyObject *self, PyObject *args)
return PyDict_SetDefault(mapping, key, defaultobj);
}

static PyObject *
dict_setdefaultref(PyObject *self, PyObject *args)
{
PyObject *obj, *key, *default_value, *result = UNINITIALIZED_PTR;
if (!PyArg_ParseTuple(args, "OOO", &obj, &key, &default_value)) {
return NULL;
}
NULLABLE(obj);
NULLABLE(key);
NULLABLE(default_value);
switch (PyDict_SetDefaultRef(obj, key, default_value, &result)) {
case -1:
assert(result == NULL);
return NULL;
case 0:
assert(result == default_value);
return result;
case 1:
return result;
default:
Py_FatalError("PyDict_SetDefaultRef() returned invalid code");
Py_UNREACHABLE();
}
}

static PyObject *
dict_delitem(PyObject *self, PyObject *args)
{
Expand Down Expand Up @@ -433,6 +458,7 @@ static PyMethodDef test_methods[] = {
{"dict_delitem", dict_delitem, METH_VARARGS},
{"dict_delitemstring", dict_delitemstring, METH_VARARGS},
{"dict_setdefault", dict_setdefault, METH_VARARGS},
{"dict_setdefaultref", dict_setdefaultref, METH_VARARGS},
{"dict_keys", dict_keys, METH_O},
{"dict_values", dict_values, METH_O},
{"dict_items", dict_items, METH_O},
Expand Down
91 changes: 71 additions & 20 deletions Objects/dictobject.c