Skip to content
Closed
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 pgvector/sparsevec.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ def _from_dict(self, d: dict[int, float], dim: int) -> None:

self._dim = int(dim)
self._indices = [int(v[0]) for v in elements]
if any(i < 0 or i >= self._dim for i in self._indices):
raise ValueError('sparsevec index out of bounds')
self._values = [float(v[1]) for v in elements]

def _from_sparse(self, arr: sparray | spmatrix, /) -> None:
Expand Down
5 changes: 5 additions & 0 deletions tests/test_sparse_vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ def test_dict(self) -> None:
def test_dict_empty(self) -> None:
assert SparseVector({}, 0).to_list() == []

@pytest.mark.parametrize('index', [-1, 3])
def test_dict_index_out_of_bounds(self, index: int) -> None:
with pytest.raises(ValueError, match='sparsevec index out of bounds'):
SparseVector({index: 1}, 3)

def test_dict_no_dimensions(self) -> None:
with pytest.raises(ValueError) as error:
SparseVector({0: 1, 2: 2, 4: 3}) # type: ignore
Expand Down