Skip to content

Commit d42b368

Browse files
authoredJun 14, 2022
[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)
1 parent 02ff1cc commit d42b368

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
@@ -40,3 +40,6 @@ struct _frozen {
4040
collection of frozen modules: */
4141

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

Diff for: ‎Python/import.c

+31
Original file line numberDiff line numberDiff line change
@@ -2632,6 +2632,37 @@ PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
26322632
return PyImport_ExtendInittab(newtab);
26332633
}
26342634

2635+
2636+
PyObject *
2637+
_PyImport_GetModuleAttr(PyObject *modname, PyObject *attrname)
2638+
{
2639+
PyObject *mod = PyImport_Import(modname);
2640+
if (mod == NULL) {
2641+
return NULL;
2642+
}
2643+
PyObject *result = PyObject_GetAttr(mod, attrname);
2644+
Py_DECREF(mod);
2645+
return result;
2646+
}
2647+
2648+
PyObject *
2649+
_PyImport_GetModuleAttrString(const char *modname, const char *attrname)
2650+
{
2651+
PyObject *pmodname = PyUnicode_FromString(modname);
2652+
if (pmodname == NULL) {
2653+
return NULL;
2654+
}
2655+
PyObject *pattrname = PyUnicode_FromString(attrname);
2656+
if (pattrname == NULL) {
2657+
Py_DECREF(pmodname);
2658+
return NULL;
2659+
}
2660+
PyObject *result = _PyImport_GetModuleAttr(pmodname, pattrname);
2661+
Py_DECREF(pattrname);
2662+
Py_DECREF(pmodname);
2663+
return result;
2664+
}
2665+
26352666
#ifdef __cplusplus
26362667
}
26372668
#endif

0 commit comments

Comments
 (0)
Please sign in to comment.