[libgpiod][PATCH 2/9] bindings: python: avoid PyObject_CallMethod during chip finalize

Vincent Fazio
2026-04-22T01:20:58Z

The PyObject_CallMethod function jumps through hoops to find the method
to call and to build a stack (if necessary) to call a given method.

In the case of finalizing the chip object, that overhead can be avoided
by simply sharing a function with `chip_close` to close the underlying
gpiod_chip object.

Signed-off-by: Vincent Fazio <vfazio@gmail.com>
---
bindings/python/gpiod/ext/chip.c | 18 ++++++++++++------
1 file changed, 12 insertions(+), 6 deletions(-)

diff --git a/bindings/python/gpiod/ext/chip.c b/bindings/python/gpiod/ext/chip.c
index 19b3a4f..9061d23 100644
--- a/bindings/python/gpiod/ext/chip.c
+++ b/bindings/python/gpiod/ext/chip.c
@@ -32,10 +32,19 @@ chip_init(chip_object *self, PyObject *args, PyObject *Py_UNUSED(ignored))
return 0;
}

+static void internal_chip_close(chip_object *self)
+{
+ if (self->chip) {
+ Py_BEGIN_ALLOW_THREADS;
+ gpiod_chip_close(self->chip);
+ Py_END_ALLOW_THREADS;
+ self->chip = NULL;
+ }
+}
+
static void chip_finalize(chip_object *self)
{
- if (self->chip)
- PyObject_CallMethod((PyObject *)self, "close", "");
+ internal_chip_close(self);
}

static PyObject *chip_path(chip_object *self, void *Py_UNUSED(ignored))
@@ -62,10 +71,7 @@ static PyGetSetDef chip_getset[] = {

static PyObject *chip_close(chip_object *self, PyObject *Py_UNUSED(ignored))
{
- Py_BEGIN_ALLOW_THREADS;
- gpiod_chip_close(self->chip);
- Py_END_ALLOW_THREADS;
- self->chip = NULL;
+ internal_chip_close(self);

Py_RETURN_NONE;
}
--
2.43.0