diff --git a/numpy_ringbuffer/__init__.py b/numpy_ringbuffer/__init__.py index 90c25bd..db6c6d3 100644 --- a/numpy_ringbuffer/__init__.py +++ b/numpy_ringbuffer/__init__.py @@ -164,6 +164,10 @@ def __len__(self): def __getitem__(self, item): # handle simple (b[1]) and basic (b[np.array([1, 2, 3])]) fancy indexing specially if not isinstance(item, tuple): + if isinstance(item, int) and item < 0: + # ringbuf[-] + item = (item + self._right_index) % self._capacity + return self._arr[item] item_arr = np.asarray(item) if issubclass(item_arr.dtype.type, np.integer): item_arr = (item_arr + self._left_index) % self._capacity diff --git a/tests.py b/tests.py index feeb9ae..8f31c90 100644 --- a/tests.py +++ b/tests.py @@ -58,6 +58,20 @@ def test_getitem(self): ii = [0, 4, 3, 1, 2] np.testing.assert_equal(r[ii], expected[ii]) + def test_getitem_from_right(self): + r = RingBuffer(5, dtype=int) + r.append(1) + for num in range(2, 5): + r.append(num) + self.assertEqual(r[-1], num) + for num in range(5, 13): + r.append(num) + self.assertEqual(r[-1], num) + self.assertEqual(r[-2], num - 1) + self.assertEqual(r[-5], num - 4) + np.testing.assert_equal(r[-4:], [9, 10, 11, 12]) + np.testing.assert_equal(r[-5:-2], [8, 9, 10]) + def test_appendleft(self): r = RingBuffer(5)