Skip to content

Commit

Permalink
Improved code
Browse files Browse the repository at this point in the history
  • Loading branch information
ankane committed Jun 25, 2024
1 parent 2b89e16 commit 0cf5ca5
Showing 1 changed file with 8 additions and 6 deletions.
14 changes: 8 additions & 6 deletions pgvector/utils/sparsevec.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
import numpy as np
from struct import pack, unpack_from

NO_DEFAULT = object()


class SparseVector:
def __init__(self, value, dimensions=None, /):
def __init__(self, value, dimensions=NO_DEFAULT, /):
if value.__class__.__module__ == 'scipy.sparse._arrays':
if dimensions is not None:
if dimensions is not NO_DEFAULT:
raise ValueError('dimensions not allowed')

self._from_sparse(value)
elif isinstance(value, dict):
if dimensions is NO_DEFAULT:
raise ValueError('dimensions required')

self._from_dict(value, dimensions)
else:
if dimensions is not None:
if dimensions is not NO_DEFAULT:
raise ValueError('dimensions not allowed')

self._from_dense(value)
Expand Down Expand Up @@ -56,9 +61,6 @@ def to_binary(self):
return pack(f'>iii{nnz}i{nnz}f', self._dim, nnz, 0, *self._indices, *self._values)

def _from_dict(self, d, dim):
if dim is None:
raise ValueError('dimensions required')

elements = [(i, v) for i, v in d.items() if v != 0]
elements.sort()

Expand Down

0 comments on commit 0cf5ca5

Please sign in to comment.