From 26d394ac4708580e298eba3a305596e0393449cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Colomb?= Date: Tue, 15 Jul 2025 10:15:31 +0200 Subject: [PATCH 1/3] Refactor. --- canopen/pdo/base.py | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/canopen/pdo/base.py b/canopen/pdo/base.py index 7bef6e62..58d5d3b7 100644 --- a/canopen/pdo/base.py +++ b/canopen/pdo/base.py @@ -40,17 +40,19 @@ def __iter__(self): return iter(self.map) def __getitem__(self, key): - if isinstance(key, int) and (0x1A00 <= key <= 0x1BFF or # By TPDO ID (512) - 0x1600 <= key <= 0x17FF or # By RPDO ID (512) - 0 < key <= 512): # By PDO Index - return self.map[key] - else: - for pdo_map in self.map.values(): - try: - return pdo_map[key] - except KeyError: - # ignore if one specific PDO does not have the key and try the next one - continue + if isinstance(key, int): + if ( + 0 < key <= 512 # By PDO Index + or 0x1600 <= key <= 0x17FF # By RPDO ID (512) + or 0x1A00 <= key <= 0x1BFF # By TPDO ID (512) + ): + return self.map[key] + for pdo_map in self.map.values(): + try: + return pdo_map[key] + except KeyError: + # ignore if one specific PDO does not have the key and try the next one + continue raise KeyError(f"PDO: {key} was not found in any map") def __len__(self): From f2263daf19f60de78872dceb7c9f3b87661b0420 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Colomb?= Date: Tue, 15 Jul 2025 10:15:38 +0200 Subject: [PATCH 2/3] Raise KeyError for zero index. --- canopen/pdo/base.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/canopen/pdo/base.py b/canopen/pdo/base.py index 58d5d3b7..79ff2cf8 100644 --- a/canopen/pdo/base.py +++ b/canopen/pdo/base.py @@ -41,6 +41,8 @@ def __iter__(self): def __getitem__(self, key): if isinstance(key, int): + if key == 0: + raise KeyError("PDO index zero requested for 1-based sequence") if ( 0 < key <= 512 # By PDO Index or 0x1600 <= key <= 0x17FF # By RPDO ID (512) From 0c7606f1656749aec6fec521b2e9c1e0671b43ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Colomb?= Date: Tue, 15 Jul 2025 10:16:02 +0200 Subject: [PATCH 3/3] Add annotation. --- canopen/pdo/base.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/canopen/pdo/base.py b/canopen/pdo/base.py index 79ff2cf8..c4104143 100644 --- a/canopen/pdo/base.py +++ b/canopen/pdo/base.py @@ -39,7 +39,7 @@ def __init__(self, node: Union[LocalNode, RemoteNode]): def __iter__(self): return iter(self.map) - def __getitem__(self, key): + def __getitem__(self, key: Union[int, str]): if isinstance(key, int): if key == 0: raise KeyError("PDO index zero requested for 1-based sequence")