summaryrefslogtreecommitdiffstats
path: root/Objects
diff options
context:
space:
mode:
authorSerhiy Storchaka <storchaka@gmail.com>2023-07-11 20:04:12 (GMT)
committerGitHub <noreply@github.com>2023-07-11 20:04:12 (GMT)
commit4bf43710d1e1f19cc46b116b5d8524f6c75dabfa (patch)
treef005fe94ab083da1f9a21485f51373efa7cf8008 /Objects
parentb444bfb0a325dea8c29f7b1828233b00fbf4a1cb (diff)
downloadcpython-4bf43710d1e1f19cc46b116b5d8524f6c75dabfa.zip
cpython-4bf43710d1e1f19cc46b116b5d8524f6c75dabfa.tar.gz
cpython-4bf43710d1e1f19cc46b116b5d8524f6c75dabfa.tar.bz2
gh-106307: C API: Add PyMapping_GetOptionalItem() function (GH-106308)
Also add PyMapping_GetOptionalItemString() function.
Diffstat (limited to 'Objects')
-rw-r--r--Objects/abstract.c40
1 files changed, 40 insertions, 0 deletions
diff --git a/Objects/abstract.c b/Objects/abstract.c
index 80a4094..e595bc9 100644
--- a/Objects/abstract.c
+++ b/Objects/abstract.c
@@ -200,6 +200,30 @@ PyObject_GetItem(PyObject *o, PyObject *key)
}
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)
{
if (o == NULL || key == NULL || value == NULL) {
@@ -2367,6 +2391,22 @@ PyMapping_GetItemString(PyObject *o, const char *key)
}
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)
{
PyObject *okey;