Skip to content

Commit 6deaa5f

Browse files
committed
Improved Bit constructor code [skip ci]
1 parent e67e846 commit 6deaa5f

1 file changed

Lines changed: 24 additions & 25 deletions

File tree

pgvector/bit.py

Lines changed: 24 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ def __init__(self, value: bytes | str | list[bool] | np.ndarray[tuple[int], np.d
1313
if isinstance(value, bytes):
1414
length = 8 * len(value)
1515
data = value
16-
else:
16+
elif isinstance(value, (list, str)):
1717
if isinstance(value, list):
1818
def bit_value(v: bool) -> str:
1919
if v is True:
@@ -24,30 +24,29 @@ def bit_value(v: bool) -> str:
2424

2525
value = ''.join([bit_value(v) for v in value])
2626

27-
if isinstance(value, str):
28-
length = len(value)
29-
30-
if length % 8 != 0:
31-
value += '0' * (8 - (length % 8))
32-
33-
try:
34-
data = int(value, 2).to_bytes(len(value) // 8, byteorder='big')
35-
except ValueError:
36-
raise ValueError('expected bit string')
37-
elif NUMPY_AVAILABLE and isinstance(value, np.ndarray):
38-
if value.dtype != np.bool:
39-
# skip error for result of np.unpackbits
40-
if value.dtype != np.uint8 or np.any(value > 1):
41-
raise ValueError('expected elements to be boolean')
42-
value = value.astype(bool)
43-
44-
if value.ndim != 1:
45-
raise ValueError('expected ndim to be 1')
46-
47-
length = len(value)
48-
data = np.packbits(value).tobytes()
49-
else:
50-
raise ValueError('expected bytes, str, list, or ndarray')
27+
length = len(value)
28+
29+
if length % 8 != 0:
30+
value += '0' * (8 - (length % 8))
31+
32+
try:
33+
data = int(value, 2).to_bytes(len(value) // 8, byteorder='big')
34+
except ValueError:
35+
raise ValueError('expected bit string')
36+
elif NUMPY_AVAILABLE and isinstance(value, np.ndarray):
37+
if value.dtype != np.bool:
38+
# skip error for result of np.unpackbits
39+
if value.dtype != np.uint8 or np.any(value > 1):
40+
raise ValueError('expected elements to be boolean')
41+
value = value.astype(bool)
42+
43+
if value.ndim != 1:
44+
raise ValueError('expected ndim to be 1')
45+
46+
length = len(value)
47+
data = np.packbits(value).tobytes()
48+
else:
49+
raise ValueError('expected bytes, str, list, or ndarray')
5150

5251
self._value = pack('>i', length) + data
5352

0 commit comments

Comments
 (0)