[libgpiod][PATCH 6/9] bindings: python: use PyImport_ImportModuleAttrString when available

Vincent Fazio
2026-04-22T01:21:02Z

Commit 035ad74fdd introduced Py_gpiod_GetModuleAttrString as a way to
get a module's attribute and was inspired by CPython's internal function
_PyImport_GetModuleAttrString.

CPython 3.14 added PyImport_ImportModuleAttrString to the public API [0]
which allows us to use the standard function when available.

[0]: https://github.com/python/cpython/pull/128912

Signed-off-by: Vincent Fazio <vfazio@gmail.com>
---
bindings/python/gpiod/ext/common.c | 3 +++
bindings/python/gpiod/ext/internal.h | 10 ++++++++--
2 files changed, 11 insertions(+), 2 deletions(-)

diff --git a/bindings/python/gpiod/ext/common.c b/bindings/python/gpiod/ext/common.c
index 7d2dda7..fc28e96 100644
--- a/bindings/python/gpiod/ext/common.c
+++ b/bindings/python/gpiod/ext/common.c
@@ -64,6 +64,8 @@ PyObject *Py_gpiod_SetErrFromErrno(void)
return PyErr_SetFromErrno(exc);
}

+/* TODO: remove when 3.14 is the minimum version */
+#if PY_VERSION_HEX < 0x030E0000
PyObject *Py_gpiod_GetModuleAttrString(const char *modname,
const char *attrname)
{
@@ -78,6 +80,7 @@ PyObject *Py_gpiod_GetModuleAttrString(const char *modname,

return attribute;
}
+#endif

unsigned int Py_gpiod_PyLongAsUnsignedInt(PyObject *pylong)
{
diff --git a/bindings/python/gpiod/ext/internal.h b/bindings/python/gpiod/ext/internal.h
index 15aedfb..2996884 100644
--- a/bindings/python/gpiod/ext/internal.h
+++ b/bindings/python/gpiod/ext/internal.h
@@ -8,8 +8,6 @@
#include <Python.h>

PyObject *Py_gpiod_SetErrFromErrno(void);
-PyObject *Py_gpiod_GetModuleAttrString(const char *modname,
- const char *attrname);
unsigned int Py_gpiod_PyLongAsUnsignedInt(PyObject *pylong);
void Py_gpiod_dealloc(PyObject *self);
PyObject *Py_gpiod_MakeRequestObject(struct gpiod_line_request *request,
@@ -17,4 +15,12 @@ PyObject *Py_gpiod_MakeRequestObject(struct gpiod_line_request *request,
struct gpiod_line_config *Py_gpiod_LineConfigGetData(PyObject *obj);
struct gpiod_line_settings *Py_gpiod_LineSettingsGetData(PyObject *obj);

+#if PY_VERSION_HEX >= 0x030E0000
+/* Alias to standard function available in 3.14 */
+#define Py_gpiod_GetModuleAttrString PyImport_ImportModuleAttrString
+#else
+PyObject *Py_gpiod_GetModuleAttrString(const char *modname,
+ const char *attrname);
+#endif /* PY_VERSION_HEX >= 0x030E0000 */
+
#endif /* __LIBGPIOD_PYTHON_MODULE_H__ */
--
2.43.0