Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
[3.11] gh-93741: Add private C API _PyImport_GetModuleAttrString() (G…
…H-93742)

It combines PyImport_ImportModule() and PyObject_GetAttrString()
and saves 4-6 lines of code on every use.

Add also _PyImport_GetModuleAttr() which takes Python strings as arguments.
(cherry picked from commit 6fd4c8e)

Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
  • Loading branch information
serhiy-storchaka committed Jun 14, 2022
commit 96c4a2c053396f8720416df19b3b1cd5bbd88dcc
3 changes: 3 additions & 0 deletions Include/cpython/import.h
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,6 @@ struct _frozen {
collection of frozen modules: */

PyAPI_DATA(const struct _frozen *) PyImport_FrozenModules;

PyAPI_DATA(PyObject *) _PyImport_GetModuleAttr(PyObject *, PyObject *);
PyAPI_DATA(PyObject *) _PyImport_GetModuleAttrString(const char *, const char *);
31 changes: 31 additions & 0 deletions Python/import.c
Original file line number Diff line number Diff line change
Expand Up @@ -2632,6 +2632,37 @@ PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
return PyImport_ExtendInittab(newtab);
}


PyObject *
_PyImport_GetModuleAttr(PyObject *modname, PyObject *attrname)
{
PyObject *mod = PyImport_Import(modname);
if (mod == NULL) {
return NULL;
}
PyObject *result = PyObject_GetAttr(mod, attrname);
Py_DECREF(mod);
return result;
}

PyObject *
_PyImport_GetModuleAttrString(const char *modname, const char *attrname)
{
PyObject *pmodname = PyUnicode_FromString(modname);
if (pmodname == NULL) {
return NULL;
}
PyObject *pattrname = PyUnicode_FromString(attrname);
if (pattrname == NULL) {
Py_DECREF(pmodname);
return NULL;
}
PyObject *result = _PyImport_GetModuleAttr(pmodname, pattrname);
Py_DECREF(pattrname);
Py_DECREF(pmodname);
return result;
}

#ifdef __cplusplus
}
#endif