Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions AUTHORS.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ reporting, all input is greatly appreciated!

Code contributions:

- parijat1222q

- Alexandre Decan (AlexandreDecan)
- dhilipsiva (dhilipsiva)
- MAA (FooBarQuaxx)
Expand Down
2 changes: 2 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
5 changes: 5 additions & 0 deletions box/box_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import copy
import copyreg
import operator
import re
from collections.abc import Iterable
from os import PathLike
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -186,13 +189,15 @@ 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"):
at = min(max(index + length, 0) if index < 0 else index, length)
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)
Expand Down
96 changes: 96 additions & 0 deletions test/test_box_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"}