Commit c294dd5d by Wuwei Lin Committed by Yizhi Liu

Allow to use negative index of array in python (#2069)

* Allow to use negative index of array in python

* Support negative index in array slice

* Print index and array size in IndexError

* Fix style
parent fdf035e8
...@@ -17,10 +17,17 @@ class Array(NodeBase): ...@@ -17,10 +17,17 @@ class Array(NodeBase):
start = i.start if i.start is not None else 0 start = i.start if i.start is not None else 0
stop = i.stop if i.stop is not None else len(self) stop = i.stop if i.stop is not None else len(self)
step = i.step if i.step is not None else 1 step = i.step if i.step is not None else 1
if start < 0:
start += len(self)
if stop < 0:
stop += len(self)
return [self[idx] for idx in range(start, stop, step)] return [self[idx] for idx in range(start, stop, step)]
if i >= len(self): if i < -len(self) or i >= len(self):
raise IndexError("array index out of range") raise IndexError("Array index out of range. Array size: {}, got index {}"
.format(len(self), i))
if i < 0:
i += len(self)
return _api_internal._ArrayGetItem(self, i) return _api_internal._ArrayGetItem(self, i)
def __len__(self): def __len__(self):
......
...@@ -3,6 +3,9 @@ import tvm ...@@ -3,6 +3,9 @@ import tvm
def test_array(): def test_array():
a = tvm.convert([1,2,3]) a = tvm.convert([1,2,3])
assert len(a) == 3 assert len(a) == 3
assert a[-1].value == 3
a_slice = a[-3:-1]
assert (a_slice[0].value, a_slice[1].value) == (1, 2)
def test_array_save_load_json(): def test_array_save_load_json():
a = tvm.convert([1,2,3]) a = tvm.convert([1,2,3])
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment