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