Skip to content

Commit 34d61b7

Browse files
committed
Fix negative indices for __setitem__ in StringList
1 parent 8c881cb commit 34d61b7

File tree

2 files changed

+13
-0
lines changed

2 files changed

+13
-0
lines changed

domdf_python_tools/stringlist.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,8 @@ def __setitem__(self, index: Union[int, slice], line: Union[String, Iterable[Str
228228
if isinstance(index, int):
229229
if self and index < len(self):
230230
self.pop(index)
231+
if index < 0:
232+
index = len(self) + index + 1
231233
self.insert(index, line)
232234

233235
elif isinstance(index, slice):

tests/test_stringlist.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,17 @@ def test_start_of_line_indents(self):
118118
assert StringList("Hello\n World") == ["Hello", " World"]
119119
assert StringList("Hello\n World", convert_indents=True) == ["Hello", "\tWorld"]
120120

121+
def test_negative_getitem(self):
122+
sl = StringList(['', '', "hello", "world", '', '', 'abc', "1234"])
123+
124+
assert sl[-1] == "1234"
125+
sl[-1] += "5678"
126+
assert sl == ['', '', "hello", "world", '', '', 'abc', "12345678"]
127+
128+
assert sl[-2] == "abc"
129+
sl[-2] += "def"
130+
assert sl == ['', '', "hello", "world", '', '', 'abcdef', "12345678"]
131+
121132
def test_indent_size(self):
122133
sl = StringList(['', '', "hello", "world", '', '', '', "1234"])
123134

0 commit comments

Comments
 (0)