gh-108308: Use PyDict_GetItemRef() in moduleobject.c (#108381)

Replace PyDict_GetItemWithError() with PyDict_GetItemRef() which
returns a strong reference.

Cleanup also the function: move variable definition to their first
assignation, rename variable names to use name longer than 1
character.
This commit is contained in:
Victor Stinner 2023-08-23 23:57:40 +02:00 committed by GitHub
parent 592bacb6fc
commit 4890f65ecf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 40 additions and 28 deletions

View File

@ -510,25 +510,31 @@ PyModule_GetDict(PyObject *m)
}
PyObject*
PyModule_GetNameObject(PyObject *m)
PyModule_GetNameObject(PyObject *mod)
{
PyObject *d;
PyObject *name;
if (!PyModule_Check(m)) {
if (!PyModule_Check(mod)) {
PyErr_BadArgument();
return NULL;
}
d = ((PyModuleObject *)m)->md_dict;
if (d == NULL || !PyDict_Check(d) ||
(name = PyDict_GetItemWithError(d, &_Py_ID(__name__))) == NULL ||
!PyUnicode_Check(name))
{
PyObject *dict = ((PyModuleObject *)mod)->md_dict; // borrowed reference
if (dict == NULL || !PyDict_Check(dict)) {
goto error;
}
PyObject *name;
if (PyDict_GetItemRef(dict, &_Py_ID(__name__), &name) <= 0) {
goto error;
}
if (!PyUnicode_Check(name)) {
Py_DECREF(name);
goto error;
}
return name;
error:
if (!PyErr_Occurred()) {
PyErr_SetString(PyExc_SystemError, "nameless module");
}
return NULL;
}
return Py_NewRef(name);
}
const char *
@ -544,25 +550,31 @@ PyModule_GetName(PyObject *m)
}
PyObject*
PyModule_GetFilenameObject(PyObject *m)
PyModule_GetFilenameObject(PyObject *mod)
{
PyObject *d;
PyObject *fileobj;
if (!PyModule_Check(m)) {
if (!PyModule_Check(mod)) {
PyErr_BadArgument();
return NULL;
}
d = ((PyModuleObject *)m)->md_dict;
if (d == NULL ||
(fileobj = PyDict_GetItemWithError(d, &_Py_ID(__file__))) == NULL ||
!PyUnicode_Check(fileobj))
{
PyObject *dict = ((PyModuleObject *)mod)->md_dict; // borrowed reference
if (dict == NULL) {
goto error;
}
PyObject *fileobj;
if (PyDict_GetItemRef(dict, &_Py_ID(__file__), &fileobj) <= 0) {
goto error;
}
if (!PyUnicode_Check(fileobj)) {
Py_DECREF(fileobj);
goto error;
}
return fileobj;
error:
if (!PyErr_Occurred()) {
PyErr_SetString(PyExc_SystemError, "module filename missing");
}
return NULL;
}
return Py_NewRef(fileobj);
}
const char *