Skip to content
Open
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 src/scyjava/_convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,8 @@ def __init__(self, jobj):
JavaObject.__init__(self, jobj, _jc.List)

def __getitem__(self, key):
if isinstance(key, slice):
return [self[index] for index in range(*key.indices(len(self)))]
# NB: Even if an element cannot be converted,
# we still want Pythonic access to elements.
return to_python(self.jobj.get(key), gentle=True)
Expand Down
36 changes: 36 additions & 0 deletions tests/test_convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,42 @@


class TestConvert:
@pytest.mark.parametrize(
"selection",
[
slice(None),
slice(1, 4),
slice(-4, -1),
slice(None, None, 2),
slice(None, None, -1),
slice(4, 0, -2),
slice(-100, 100),
slice(3, 1),
],
)
def testListSlice(self, selection):
original = ["a", "b", "c", "d", "e"]
converted = to_python(to_java(original))
result = converted[selection]
assert result == original[selection]
assert all(isinstance(value, str) for value in result)
assert converted == original

def testListSliceZeroStep(self):
converted = to_python(to_java([1, 2, 3]))
with pytest.raises(ValueError, match="slice step cannot be zero"):
converted[::0]

def testEmptyListSlice(self):
converted = to_python(to_java([]))
assert converted[:] == []
assert converted[::-1] == []

def testListSliceUnconvertedElement(self):
element = jimport("java.lang.Object")()
converted = to_python(to_java([element]))
assert converted[:] == [element]

def testClass(self):
"""
Test class detection from Java objects.
Expand Down