Skip to content

Commit 0168744

Browse files
ashvardanianmobinln
andcommitted
Fix: Infinite loop over index.keys
Closes #544 Co-authored-by: Mobin Larijanian <22958029+mobinln@users.noreply.github.com>
1 parent 10b3659 commit 0168744

2 files changed

Lines changed: 16 additions & 2 deletions

File tree

python/scripts/test_index.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -403,6 +403,16 @@ def test_index_clustering(ndim, metric, quantization, dtype, batch_size):
403403
assert len(unique_clusters) >= 3 and len(unique_clusters) <= 10
404404

405405

406+
def test_index_keys_iteration():
407+
"""Test that iterating over index.keys works without infinite loop."""
408+
index = Index(ndim=3)
409+
index.add(keys=[42], vectors=np.array([0.2, 0.3, 0.5]))
410+
411+
keys_list = list(index.keys)
412+
assert len(keys_list) == 1
413+
assert keys_list[0] == 42
414+
415+
406416
def test_index_copied_memory_usage():
407417
"""Test that copy=False results in lower memory usage than copy=True."""
408418
reset_randomness()

python/usearch/index.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -459,8 +459,8 @@ def __getitem__(
459459
) -> Union[Key, np.ndarray]:
460460
if isinstance(offset_offsets_or_slice, slice):
461461
start, stop, step = offset_offsets_or_slice.indices(len(self))
462-
if step:
463-
raise
462+
if step != 1:
463+
raise ValueError("Slicing with a step is not supported")
464464
return self.index._compiled.get_keys_in_slice(start, stop - start)
465465

466466
elif isinstance(offset_offsets_or_slice, Iterable):
@@ -469,6 +469,10 @@ def __getitem__(
469469

470470
else:
471471
offset = int(offset_offsets_or_slice)
472+
if offset < 0:
473+
offset += len(self)
474+
if offset < 0 or offset >= len(self):
475+
raise IndexError("Index out of range")
472476
return self.index._compiled.get_key_at_offset(offset)
473477

474478
def __array__(self, dtype=None) -> np.ndarray:

0 commit comments

Comments
 (0)