From 40edc1fa98b3e53acf4d739d15c7539581713f8c Mon Sep 17 00:00:00 2001 From: parijat1222q <98056935+parijat1222q@users.noreply.github.com> Date: Mon, 9 Nov 2026 11:00:36 +0530 Subject: [PATCH] Preserve BoxList comments with index protocol objects --- AUTHORS.rst | 2 + CHANGES.rst | 2 + box/box_list.py | 5 +++ test/test_box_list.py | 96 +++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 105 insertions(+) diff --git a/AUTHORS.rst b/AUTHORS.rst index 9f167759..ff270fad 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -5,6 +5,8 @@ reporting, all input is greatly appreciated! Code contributions: +- parijat1222q + - Alexandre Decan (AlexandreDecan) - dhilipsiva (dhilipsiva) - MAA (FooBarQuaxx) diff --git a/CHANGES.rst b/CHANGES.rst index 237e0d98..4f103e79 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -4,6 +4,8 @@ Changelog Version 8.0.1 ------------- +* Preserve BoxList item comments when insert, pop and deletion use objects with __index__ (thanks to parijat1222q) + * Fixing #349 BoxList item comments moving to the wrong items after a box_dots deletion, e.g. del bl["[0]"] (thanks to HocVoNgThai) * Fixing #349 BoxList.sort() calling the key function twice when the list has comments (thanks to HocVoNgThai) diff --git a/box/box_list.py b/box/box_list.py index 1470aacd..f6091494 100644 --- a/box/box_list.py +++ b/box/box_list.py @@ -6,6 +6,7 @@ import copy import copyreg +import operator import re from collections.abc import Iterable from os import PathLike @@ -104,6 +105,8 @@ def __delitem__(self, key): return self.__delitem__(pos) if hasattr(self[pos], "__delitem__"): return self[pos].__delitem__(key[len(list_pos.group()) :].lstrip(".")) # type: ignore + if not isinstance(key, slice) and hasattr(type(key), "__index__"): + key = operator.index(key) length = len(self) super().__delitem__(key) self._comment_after_delete(key, length) @@ -186,6 +189,7 @@ def extend(self, iterable): self.append(item) def insert(self, index, p_object): + index = operator.index(index) length = len(self) super().insert(index, self._convert(p_object)) if self.__dict__.get("_box_comments"): @@ -193,6 +197,7 @@ def insert(self, index, p_object): self._comment_reindex(lambda k: k + 1 if k >= at else k) def pop(self, index=-1): + index = operator.index(index) length = len(self) value = super().pop(index) self._comment_after_delete(index, length) diff --git a/test/test_box_list.py b/test/test_box_list.py index 469c3e98..4291ac63 100644 --- a/test/test_box_list.py +++ b/test/test_box_list.py @@ -666,3 +666,99 @@ def test_iadd_frozen_does_not_consume_source(): data += source assert next(source) == {"value": 1} assert data == [0] + + +class _IndexOnce: + def __init__(self, value): + self.value = value + self.calls = 0 + + def __index__(self): + self.calls += 1 + if self.calls > 1: + raise AssertionError("index was evaluated more than once") + return self.value + + +@pytest.mark.parametrize("operation", ["insert", "pop", "delete"]) +@pytest.mark.parametrize("index", [0, 1, -1, -3]) +@pytest.mark.parametrize("comments", [False, True]) +def test_index_protocol_keeps_item_comments(operation, index, comments): + values = BoxList(["a", "b", "c"]) + if comments: + for position, item in enumerate(values): + values.set_comment(position, item) + expected = list(values) + key = _IndexOnce(index) + if operation == "insert": + expected.insert(index, "new") + values.insert(key, "new") + elif operation == "pop": + assert values.pop(key) == expected.pop(index) + else: + del expected[index] + del values[key] + assert key.calls == 1 + assert values == expected + for position, item in enumerate(values): + comment = {"eol": item} if comments and item != "new" else None + assert values.get_comment(position) == comment + + +@pytest.mark.parametrize("operation", ["insert", "pop", "delete"]) +@pytest.mark.parametrize("comments", [False, True]) +def test_invalid_index_does_not_change_items_or_comments(operation, comments): + class BadIndex: + def __index__(self): + raise ValueError("invalid index") + + values = BoxList(["a", "b", "c"]) + if comments: + for position, item in enumerate(values): + values.set_comment(position, item) + with pytest.raises(ValueError, match="invalid index"): + if operation == "insert": + values.insert(BadIndex(), "new") + elif operation == "pop": + values.pop(BadIndex()) + else: + del values[BadIndex()] + assert values == ["a", "b", "c"] + for position, item in enumerate(values): + assert values.get_comment(position) == ({"eol": item} if comments else None) + + +@pytest.mark.parametrize("index", [-100, 100]) +@pytest.mark.parametrize("comments", [False, True]) +def test_insert_index_protocol_clamps_and_moves_comments(index, comments): + values = BoxList(["a", "b"]) + if comments: + values.set_comment(0, "a") + values.set_comment(1, "b") + expected = list(values) + expected.insert(index, "new") + key = _IndexOnce(index) + values.insert(key, "new") + assert key.calls == 1 + assert values == expected + for position, item in enumerate(values): + expected_comment = {"eol": item} if comments and item != "new" else None + assert values.get_comment(position) == expected_comment + + +@pytest.mark.parametrize("operation", ["pop", "delete"]) +@pytest.mark.parametrize("index", [-100, 100]) +def test_out_of_bounds_index_preserves_comments(operation, index): + values = BoxList(["a", "b"]) + values.set_comment(0, "a") + values.set_comment(1, "b") + key = _IndexOnce(index) + with pytest.raises(IndexError): + if operation == "pop": + values.pop(key) + else: + del values[key] + assert key.calls == 1 + assert values == ["a", "b"] + assert values.get_comment(0) == {"eol": "a"} + assert values.get_comment(1) == {"eol": "b"}