mirror of
https://github.com/python/cpython.git
synced 2025-12-09 10:37:17 +00:00
gh-106307: C API: Add PyMapping_GetOptionalItem() function (GH-106308)
Also add PyMapping_GetOptionalItemString() function.
This commit is contained in:
parent
b444bfb0a3
commit
4bf43710d1
15 changed files with 739 additions and 896 deletions
|
|
@ -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)
|
||||
{
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue