[C API] Add PyDict_ContainsString() function · Issue #108314 · python/cpython (original) (raw)
Feature or enhancement
Has this already been discussed elsewhere?
No response given
Links to previous discussion of this feature:
No response
Proposal:
Most, if not all, PyDict C APIs have a "String" flavor where the key argument is expressed as a UTF-8 encoded bytes string. But the PyDict_Contains()
API is missing such variant.
I suppose that it was not proposed before since PyDict_GetItemString(dict, key) != NULL
can already be used. My problem is that PyDict_GetItemString()
ignores errors: I would like to report errors.
The newly added PyDict_GetItemStringRef()
can be used to check if a dictionary has a key and report errors, but it requires calling Py_DECREF()
which is not convenient. Example:
PyObject *value;
if (PyDict_GetItemStringRef(dict, key, &value) < 0) {
// ... handle error ...
}
int has_value = (value != NULL);
Py_XDECREF(value);
// ... use has_value ...
I would like to be able to replace this code with:
int has_value = PyDict_ContainsString(dict, key);
if (has_value < 0) {
// ... handle error ...
}
// ... use has_value ...
There is no need to INCREF/DECREF just to check if a dictionary has a key.