Skip to content

Commit 48b27ba

Browse files
authored
Adds indexing by name for ClassLists (#54)
* added get item to classlists with wider range of inputs * added test for completeness
1 parent fc67011 commit 48b27ba

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

RATapi/classlist.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,15 @@ def __str__(self):
7979
output = str(self.data)
8080
return output
8181

82+
def __getitem__(self, index: Union[int, slice, str, object]) -> object:
83+
"""Get an item by its index, name, a slice, or the object itself."""
84+
if isinstance(index, (int, slice)):
85+
return self.data[index]
86+
elif isinstance(index, (str, object)):
87+
return self.data[self.index(index)]
88+
else:
89+
raise IndexError("ClassLists can only be indexed by integers, slices, name strings, or objects.")
90+
8291
def __setitem__(self, index: int, item: object) -> None:
8392
"""Replace the object at an existing index of the ClassList."""
8493
self._setitem(index, item)

tests/test_classlist.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -880,3 +880,13 @@ def test_determine_class_handle(input_list: ClassList, expected_type: type) -> N
880880
for all elements in the ClassList.
881881
"""
882882
assert ClassList._determine_class_handle(input_list) == expected_type
883+
884+
885+
def test_get_item(two_name_class_list):
886+
"""Test item names can be gotten by name, index, object or slice."""
887+
assert two_name_class_list[0] == two_name_class_list["Alice"]
888+
assert two_name_class_list[1] == two_name_class_list["Bob"]
889+
assert two_name_class_list[:] == two_name_class_list
890+
alice = InputAttributes(name="Alice")
891+
assert two_name_class_list[alice] == two_name_class_list["Alice"]
892+
assert two_name_class_list[alice] == two_name_class_list[0]

0 commit comments

Comments
 (0)