Skip to content

Commit de0e644

Browse files
authored
Fix OD item lookup evaluating subobject's length (fixes #588) (#589)
If the lookup by name returns an object (not None), the boolean expression still checks whether that object is equivalent to boolean True. This needlessly calls the object's __len__() method, while what we're interested in is just whether an object was found.
1 parent 7fb914a commit de0e644

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

canopen/objectdictionary/__init__.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,9 @@ def __getitem__(
133133
self, index: Union[int, str]
134134
) -> Union[ODArray, ODRecord, ODVariable]:
135135
"""Get object from object dictionary by name or index."""
136-
item = self.names.get(index) or self.indices.get(index)
136+
item = self.names.get(index)
137+
if item is None:
138+
item = self.indices.get(index)
137139
if item is None:
138140
if isinstance(index, str) and '.' in index:
139141
idx, sub = index.split('.', maxsplit=1)

test/test_od.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,18 @@ def test_get_item_dot(self):
249249
self.assertEqual(test_od["Test Array.Test Variable"], member1)
250250
self.assertEqual(test_od["Test Array.Test Variable 2"], member2)
251251

252+
def test_get_item_index(self):
253+
test_od = od.ObjectDictionary()
254+
array = od.ODArray("Test Array", 0x1000)
255+
test_od.add_object(array)
256+
item = test_od[0x1000]
257+
self.assertIsInstance(item, od.ODArray)
258+
self.assertIs(item, array)
259+
item = test_od["Test Array"]
260+
self.assertIsInstance(item, od.ODArray)
261+
self.assertIs(item, array)
262+
263+
252264
class TestArray(unittest.TestCase):
253265

254266
def test_subindexes(self):

0 commit comments

Comments
 (0)