diff options
author | Serhiy Storchaka <storchaka@gmail.com> | 2022-06-14 05:51:39 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-06-14 05:51:39 (GMT) |
commit | d42b3689f4a14694f5b1ff75c155141102aa2557 (patch) | |
tree | a8adaba47e89c98c6be3d0040f94ea909e321ba4 | |
parent | 02ff1ccfb702e740d08cd4f546cf0e51f929c718 (diff) | |
download | cpython-d42b3689f4a14694f5b1ff75c155141102aa2557.zip cpython-d42b3689f4a14694f5b1ff75c155141102aa2557.tar.gz cpython-d42b3689f4a14694f5b1ff75c155141102aa2557.tar.bz2 |
[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 6fd4c8ec7740523bb81191c013118d9d6959bc9d)
-rw-r--r-- | Include/cpython/import.h | 3 | ||||
-rw-r--r-- | Python/import.c | 31 |
2 files changed, 34 insertions, 0 deletions
diff --git a/Include/cpython/import.h b/Include/cpython/import.h index ef6be68..a69b4f3 100644 --- a/Include/cpython/import.h +++ b/Include/cpython/import.h @@ -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 *); diff --git a/Python/import.c b/Python/import.c index 4b6d6d1..ca728c4 100644 --- a/Python/import.c +++ b/Python/import.c @@ -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 |