bpo-42152: Use PyDict_Contains and PyDict_SetDefault if appropriate. (GH-22986)
If PyDict_GetItemWithError is only used to check whether the key is in dict,
it is better to use PyDict_Contains instead.
And if it is used in combination with PyDict_SetItem, PyDict_SetDefault can
replace the combination.
diff --git a/Modules/posixmodule.c b/Modules/posixmodule.c
index 6ce0bcb..ccd64d6 100644
--- a/Modules/posixmodule.c
+++ b/Modules/posixmodule.c
@@ -1526,13 +1526,11 @@ convertenviron(void)
Py_DECREF(d);
return NULL;
}
- if (PyDict_GetItemWithError(d, k) == NULL) {
- if (PyErr_Occurred() || PyDict_SetItem(d, k, v) != 0) {
- Py_DECREF(v);
- Py_DECREF(k);
- Py_DECREF(d);
- return NULL;
- }
+ if (PyDict_SetDefault(d, k, v) == NULL) {
+ Py_DECREF(v);
+ Py_DECREF(k);
+ Py_DECREF(d);
+ return NULL;
}
Py_DECREF(k);
Py_DECREF(v);