Skip to contentSkip to conversation

bindings: python: parse non-tuple Iterable keys

PATCH Applied Vincent Fazio 2 participants 4 messages Sep 2, 2025 – Sep 8, 2025 GPIO

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 bindings: python: parse non-tuple Iterable keys

When chip.request_lines was modified to allow Iterables instead of only tuples, the code that checked for duplicate line entries in the config argument was not updated to account for the expanded types.

If the config argument had a key that was not a tuple, str, or int, a TypeError would be raised when resolving the line offset.

Refactor the code the resolves IDs to offsets into a separate function to make the logic a bit clearer and to account for the widened types.

Fixes 8f62e6c45355 ("bindings: python: loosen type requirements in public API")
---
 bindings/python/gpiod/chip.py               | 23 ++++++++++++++-------
 bindings/python/tests/tests_line_request.py |  4 ++++
 2 files changed, 19 insertions(+), 8 deletions(-)
bindings/python/gpiod/chip.py +15 -8
index 5641343..cccfb03 100644
@@ -236,6 +236,20 @@ class Chip:
         self._check_closed()
         return cast(_ext.Chip, self._chip).read_info_event()
 
+    def _resolve_config_keys_to_offsets(
+        self,
+        config_keys: Iterable[Union[Iterable[Union[int, str]], int, str]],
+    ) -> list[int]:
+        offsets: list[int] = list()
+        for key in config_keys:
+            # perform strict int/str check since str is also Iterable
+            if isinstance(key, (int, str)):
+                offsets.append(self.line_offset_from_id(key))
+            else:  # key is an iterable with multiple IDs to resolve
+                for item in key:
+                    offsets.append(self.line_offset_from_id(item))
+        return offsets
+
     def request_lines(
         self,
         config: dict[
@@ -271,14 +285,7 @@ class Chip:
 
         # Sanitize lines - don't allow offset repetitions or offset-name conflicts.
         for offset, count in Counter(
-            [
-                self.line_offset_from_id(line)
-                for line in (
-                    lambda t: [
-                        j for i in (t) for j in (i if isinstance(i, tuple) else (i,))
-                    ]
-                )(tuple(config.keys()))
-            ]
+            self._resolve_config_keys_to_offsets(config_keys=config.keys())
         ).items():
             if count != 1:
                 raise ValueError(
bindings/python/tests/tests_line_request.py +4 -0
index afee644..217c299 100644
@@ -101,6 +101,10 @@ class ChipLineRequestWorks(TestCase):
         with self.chip.request_lines(config={(4): None}) as req:
             self.assertEqual(req.offsets, [4])
 
+    def test_request_single_offset_as_frozenset(self) -> None:
+        with self.chip.request_lines(config={frozenset([4]): None}) as req:
+            self.assertEqual(req.offsets, [4])
+
     def test_request_by_name(self) -> None:
         with self.chip.request_lines(config={(1, 2, "foo", "bar"): None}) as req:
             self.assertEqual(req.offsets, [1, 2, 5, 7])
Signature · 1 line
2.43.0
#1 lore raw
Quoted 47 lines · Vincent Fazio

When chip.request_lines was modified to allow Iterables instead of only tuples, the code that checked for duplicate line entries in the config argument was not updated to account for the expanded types.

If the config argument had a key that was not a tuple, str, or int, a TypeError would be raised when resolving the line offset.

Refactor the code the resolves IDs to offsets into a separate function to make the logic a bit clearer and to account for the widened types.

Fixes 8f62e6c45355 ("bindings: python: loosen type requirements in public API")
---
 bindings/python/gpiod/chip.py               | 23 ++++++++++++++-------
 bindings/python/tests/tests_line_request.py |  4 ++++
 2 files changed, 19 insertions(+), 8 deletions(-)
bindings/python/gpiod/chip.py +14 -0
index 5641343..cccfb03 100644
@@ -236,6 +236,20 @@ class Chip:
         self._check_closed()
         return cast(_ext.Chip, self._chip).read_info_event()
 
+    def _resolve_config_keys_to_offsets(
+        self,
+        config_keys: Iterable[Union[Iterable[Union[int, str]], int, str]],
+    ) -> list[int]:
+        offsets: list[int] = list()
+        for key in config_keys:
+            # perform strict int/str check since str is also Iterable
+            if isinstance(key, (int, str)):
+                offsets.append(self.line_offset_from_id(key))
+            else:  # key is an iterable with multiple IDs to resolve
+                for item in key:
+                    offsets.append(self.line_offset_from_id(item))
+        return offsets
+
     def request_lines(
         self,
         config: dict[
@@ -271,14 +285,7 @@ class Chip:
 
         # Sanitize lines - don't allow offset repetitions or offset-name conflicts.

bindings/python/gpiod/chip.py class Chip: · line 288

Quoted 10 lines
bindings/python/gpiod/chip.py +1 -8
         for offset, count in Counter(
-            [
-                self.line_offset_from_id(line)
-                for line in (
-                    lambda t: [
-                        j for i in (t) for j in (i if isinstance(i, tuple) else (i,))
-                    ]
-                )(tuple(config.keys()))
-            ]
+            self._resolve_config_keys_to_offsets(config_keys=config.keys())

This looks good, just a quick question: is there any particular reason to use a named argument here? Looks like a positional parameter would work just fine and stay pretty clear as the method only takes one.

Bart

Quoted 22 lines
bindings/python/gpiod/chip.py +0 -0
         ).items():
             if count != 1:
                 raise ValueError(
bindings/python/tests/tests_line_request.py +4 -1
index afee644..217c299 100644
@@ -101,6 +101,10 @@ class ChipLineRequestWorks(TestCase):
         with self.chip.request_lines(config={(4): None}) as req:
             self.assertEqual(req.offsets, [4])
 
+    def test_request_single_offset_as_frozenset(self) -> None:
+        with self.chip.request_lines(config={frozenset([4]): None}) as req:
+            self.assertEqual(req.offsets, [4])
+
     def test_request_by_name(self) -> None:
         with self.chip.request_lines(config={(1, 2, "foo", "bar"): None}) as req:
             self.assertEqual(req.offsets, [1, 2, 5, 7])
--

2.43.0

#2 lore raw
Quoted 12 lines

bindings/python/gpiod/chip.py class Chip: · line 288

Quoted 11 lines

# Sanitize lines - don't allow offset repetitions or offset-name conflicts. for offset, count in Counter(

bindings/python/gpiod/chip.py +1 -8
-            [
-                self.line_offset_from_id(line)
-                for line in (
-                    lambda t: [
-                        j for i in (t) for j in (i if isinstance(i, tuple) else (i,))
-                    ]
-                )(tuple(config.keys()))
-            ]
+            self._resolve_config_keys_to_offsets(config_keys=config.keys())
Quoted 4 lines

This looks good, just a quick question: is there any particular reason to use a named argument here? Looks like a positional parameter would work just fine and stay pretty clear as the method only takes one.

No specific reason, it has just become my habit to use named arguments even if it's not a kwarg.

Providing the name for a positional argument allows them to be declared in any order should new arguments be added and is a bit more self-documenting.

Granted, in a function that's only ever expected to take a single argument, it's probably overkill.

If it looks ok otherwise and you intend to accept the patch, please feel free to amend the patch to remove the named argument. Otherwise I can submit a v2.

-Vincent

#3 lore raw
In reply to Vincent Fazio

From: Bartosz Golaszewski <[email protected]>

Quoted 8 lines · Vincent Fazio

When chip.request_lines was modified to allow Iterables instead of only tuples, the code that checked for duplicate line entries in the config argument was not updated to account for the expanded types.

If the config argument had a key that was not a tuple, str, or int, a TypeError would be raised when resolving the line offset.

[...]

Applied, thanks!

[1/1] bindings: python: parse non-tuple Iterable keys

      https://git.kernel.org/brgl/libgpiod/c/1f2ba0deabb8bf79e8bcef849f839eea63303e57

Best regards,

Signature · 1 line
Bartosz Golaszewski <[email protected]>