Add PyDict_ContainsString() function by vstinner · Pull Request #71 · python/pythoncapi-compat
static PyObject * test_dict_getitemref(PyObject *Py_UNUSED(module), PyObject *Py_UNUSED(args)) test_dict_api(PyObject *Py_UNUSED(module), PyObject *Py_UNUSED(args)) { assert(!PyErr_Occurred());
missing_key = PyUnicode_FromString("missing_key"); if (missing_key == NULL) { goto error; }
invalid_key = PyList_New(0); // not hashable key if (invalid_key == NULL) { goto error; }
value = PyUnicode_FromString("value"); if (value == NULL) { goto error;
// test PyDict_Contains() assert(PyDict_Contains(dict, key) == 1); assert(PyDict_Contains(dict, missing_key) == 0);
// test PyDict_ContainsString() assert(PyDict_ContainsString(dict, "key") == 1); assert(PyDict_ContainsString(dict, "missing_key") == 0); assert(PyDict_ContainsString(dict, "\xff") == -1); assert(PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)); PyErr_Clear();
// test PyDict_GetItemRef(), key is present get_value = Py_Ellipsis; // marker value assert(PyDict_GetItemRef(dict, key, &get_value) == 1);
// test PyDict_GetItemRef(), invalid dict invalid_dict = key; // borrowed reference get_value = Py_Ellipsis; // marker value assert(PyDict_GetItemRef(invalid_dict, key, &get_value) == -1); assert(PyErr_ExceptionMatches(PyExc_SystemError));
invalid_key = PyList_New(0); // not hashable key if (invalid_key == NULL) { goto error; }
// test PyDict_GetItemRef(), invalid key get_value = Py_Ellipsis; // marker value assert(PyDict_GetItemRef(dict, invalid_key, &get_value) == -1);