From b5f00b0305e9d7115e02bc922419e1a38c078d41 Mon Sep 17 00:00:00 2001 From: Bit0r Date: Thu, 18 Apr 2024 23:49:20 +0800 Subject: [PATCH 1/2] feat: Add support for accessing nested items in BoxList using numpy-style tuple indexing. --- box/box_list.py | 5 +++++ test/test_box_list.py | 2 ++ 2 files changed, 7 insertions(+) diff --git a/box/box_list.py b/box/box_list.py index 048b014..f70b711 100644 --- a/box/box_list.py +++ b/box/box_list.py @@ -65,6 +65,11 @@ def __getitem__(self, item): if len(list_pos.group()) == len(item): return value return value.__getitem__(item[len(list_pos.group()) :].lstrip(".")) + if isinstance(item, tuple): + result = self + for i in item: + result = result[i] + return result return super().__getitem__(item) def __delitem__(self, key): diff --git a/test/test_box_list.py b/test/test_box_list.py index 536520f..f925d80 100644 --- a/test/test_box_list.py +++ b/test/test_box_list.py @@ -35,6 +35,8 @@ def test_box_list(self): assert new_list[-1].item == 22 new_list.append([{"bad_item": 33}]) assert new_list[-1][0].bad_item == 33 + new_list[-1].append([{"bad_item": 33}]) + assert new_list[-1, -1, 0].bad_item == 33 assert repr(new_list).startswith("BoxList(") for x in new_list.to_list(): assert not isinstance(x, (BoxList, Box)) From f9da2a2a8e335a2cbe2af341c46983f7caf1c0c8 Mon Sep 17 00:00:00 2001 From: Bit0r Date: Mon, 29 Apr 2024 00:39:08 +0800 Subject: [PATCH 2/2] Add error indexing hints and unit tests. --- box/box_list.py | 7 +++++-- test/test_box_list.py | 2 ++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/box/box_list.py b/box/box_list.py index f70b711..1850471 100644 --- a/box/box_list.py +++ b/box/box_list.py @@ -67,8 +67,11 @@ def __getitem__(self, item): return value.__getitem__(item[len(list_pos.group()) :].lstrip(".")) if isinstance(item, tuple): result = self - for i in item: - result = result[i] + for idx in item: + if isinstance(result, list): + result = result[idx] + else: + raise BoxTypeError(f"Cannot numpy-style indexing on {type(result).__name__}.") return result return super().__getitem__(item) diff --git a/test/test_box_list.py b/test/test_box_list.py index f925d80..1b7bfa3 100644 --- a/test/test_box_list.py +++ b/test/test_box_list.py @@ -37,6 +37,8 @@ def test_box_list(self): assert new_list[-1][0].bad_item == 33 new_list[-1].append([{"bad_item": 33}]) assert new_list[-1, -1, 0].bad_item == 33 + bx = Box({0: {1: {2: {3: 3}}}, (0, 1, 2, 3): 4}) + assert bx[0, 1, 2, 3] == 4 assert repr(new_list).startswith("BoxList(") for x in new_list.to_list(): assert not isinstance(x, (BoxList, Box))