gh-106307: C API: Add PyMapping_GetOptionalItem() function (GH-106308)

Also add PyMapping_GetOptionalItemString() function.
This commit is contained in:
Serhiy Storchaka 2023-07-11 23:04:12 +03:00 committed by GitHub
parent b444bfb0a3
commit 4bf43710d1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
15 changed files with 739 additions and 896 deletions

View file

@ -199,6 +199,30 @@ PyObject_GetItem(PyObject *o, PyObject *key)
return type_error("'%.200s' object is not subscriptable", o);
}
int
PyMapping_GetOptionalItem(PyObject *obj, PyObject *key, PyObject **result)
{
if (PyDict_CheckExact(obj)) {
*result = PyDict_GetItemWithError(obj, key); /* borrowed */
if (*result) {
Py_INCREF(*result);
return 1;
}
return PyErr_Occurred() ? -1 : 0;
}
*result = PyObject_GetItem(obj, key);
if (*result) {
return 1;
}
assert(PyErr_Occurred());
if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
return -1;
}
PyErr_Clear();
return 0;
}
int
PyObject_SetItem(PyObject *o, PyObject *key, PyObject *value)
{
@ -2366,6 +2390,22 @@ PyMapping_GetItemString(PyObject *o, const char *key)
return r;
}
int
PyMapping_GetOptionalItemString(PyObject *obj, const char *key, PyObject **result)
{
if (key == NULL) {
null_error();
return -1;
}
PyObject *okey = PyUnicode_FromString(key);
if (okey == NULL) {
return -1;
}
int rc = PyMapping_GetOptionalItem(obj, okey, result);
Py_DECREF(okey);
return rc;
}
int
PyMapping_SetItemString(PyObject *o, const char *key, PyObject *value)
{