Skip to content

Commit ff2109a

Browse files
Fix slicing converted Java lists
1 parent 50092cb commit ff2109a

2 files changed

Lines changed: 38 additions & 0 deletions

File tree

‎src/scyjava/_convert.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,8 @@ def __init__(self, jobj):
435435
JavaObject.__init__(self, jobj, _jc.List)
436436

437437
def __getitem__(self, key):
438+
if isinstance(key, slice):
439+
return [self[index] for index in range(*key.indices(len(self)))]
438440
# NB: Even if an element cannot be converted,
439441
# we still want Pythonic access to elements.
440442
return to_python(self.jobj.get(key), gentle=True)

‎tests/test_convert.py‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,42 @@
2929

3030

3131
class TestConvert:
32+
@pytest.mark.parametrize(
33+
"selection",
34+
[
35+
slice(None),
36+
slice(1, 4),
37+
slice(-4, -1),
38+
slice(None, None, 2),
39+
slice(None, None, -1),
40+
slice(4, 0, -2),
41+
slice(-100, 100),
42+
slice(3, 1),
43+
],
44+
)
45+
def testListSlice(self, selection):
46+
original = ["a", "b", "c", "d", "e"]
47+
converted = to_python(to_java(original))
48+
result = converted[selection]
49+
assert result == original[selection]
50+
assert all(isinstance(value, str) for value in result)
51+
assert converted == original
52+
53+
def testListSliceZeroStep(self):
54+
converted = to_python(to_java([1, 2, 3]))
55+
with pytest.raises(ValueError, match="slice step cannot be zero"):
56+
converted[::0]
57+
58+
def testEmptyListSlice(self):
59+
converted = to_python(to_java([]))
60+
assert converted[:] == []
61+
assert converted[::-1] == []
62+
63+
def testListSliceUnconvertedElement(self):
64+
element = jimport("java.lang.Object")()
65+
converted = to_python(to_java([element]))
66+
assert converted[:] == [element]
67+
3268
def testClass(self):
3369
"""
3470
Test class detection from Java objects.

0 commit comments

Comments
 (0)