Skip to content

Commit 968b238

Browse files
[3.11] gh-93741: Add private C API _PyImport_GetModuleAttrString() (GH-93742) (GH-93792)
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) (cherry picked from commit d42b368) Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
1 parent e929dae commit 968b238

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

Diff for: Include/cpython/import.h

+3
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,6 @@ struct _frozen {
4141
collection of frozen modules: */
4242

4343
PyAPI_DATA(const struct _frozen *) PyImport_FrozenModules;
44+
45+
PyAPI_DATA(PyObject *) _PyImport_GetModuleAttr(PyObject *, PyObject *);
46+
PyAPI_DATA(PyObject *) _PyImport_GetModuleAttrString(const char *, const char *);

Diff for: Python/import.c

+31
Original file line numberDiff line numberDiff line change
@@ -2294,6 +2294,37 @@ PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
22942294
return PyImport_ExtendInittab(newtab);
22952295
}
22962296

2297+
2298+
PyObject *
2299+
_PyImport_GetModuleAttr(PyObject *modname, PyObject *attrname)
2300+
{
2301+
PyObject *mod = PyImport_Import(modname);
2302+
if (mod == NULL) {
2303+
return NULL;
2304+
}
2305+
PyObject *result = PyObject_GetAttr(mod, attrname);
2306+
Py_DECREF(mod);
2307+
return result;
2308+
}
2309+
2310+
PyObject *
2311+
_PyImport_GetModuleAttrString(const char *modname, const char *attrname)
2312+
{
2313+
PyObject *pmodname = PyUnicode_FromString(modname);
2314+
if (pmodname == NULL) {
2315+
return NULL;
2316+
}
2317+
PyObject *pattrname = PyUnicode_FromString(attrname);
2318+
if (pattrname == NULL) {
2319+
Py_DECREF(pmodname);
2320+
return NULL;
2321+
}
2322+
PyObject *result = _PyImport_GetModuleAttr(pmodname, pattrname);
2323+
Py_DECREF(pattrname);
2324+
Py_DECREF(pmodname);
2325+
return result;
2326+
}
2327+
22972328
#ifdef __cplusplus
22982329
}
22992330
#endif

0 commit comments

Comments
 (0)