Skip to content

Commit f3fb971

Browse files
authored
Improve error message on invalid Vector init overload invocation (#1285)
1 parent c4a5aa7 commit f3fb971

File tree

1 file changed

+44
-4
lines changed

1 file changed

+44
-4
lines changed

src/neo4j/vector.py

Lines changed: 44 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
from __future__ import annotations as _
1919

2020
import abc as _abc
21+
import contextlib as _contextlib
22+
import inspect as _inspect
2123
import struct as _struct
2224
import sys as _sys
2325
from enum import Enum as _Enum
@@ -176,13 +178,51 @@ def __init__(self, data: _pa.Array, /) -> None: ...
176178

177179
def __init__(self, data, *args, **kwargs) -> None:
178180
if isinstance(data, (bytes, bytearray)):
179-
self._set_bytes(bytes(data), *args, **kwargs)
181+
with self._checked_init_overload(
182+
self._set_bytes, data, args, kwargs
183+
):
184+
self._set_bytes(bytes(data), *args, **kwargs)
180185
elif _np is not None and isinstance(data, _np.ndarray):
181-
self._set_numpy(data, *args, **kwargs)
186+
with self._checked_init_overload(
187+
self._set_numpy, data, args, kwargs
188+
):
189+
self._set_numpy(data, *args, **kwargs)
182190
elif _pa is not None and isinstance(data, _pa.Array):
183-
self._set_pyarrow(data, *args, **kwargs)
191+
with self._checked_init_overload(
192+
self._set_pyarrow, data, args, kwargs
193+
):
194+
self._set_pyarrow(data, *args, **kwargs)
184195
else:
185-
self._set_native(data, *args, **kwargs)
196+
with self._checked_init_overload(
197+
self._set_native, data, args, kwargs
198+
):
199+
self._set_native(data, *args, **kwargs)
200+
201+
@staticmethod
202+
@_contextlib.contextmanager
203+
def _checked_init_overload(
204+
setter: _t.Callable[..., None],
205+
data,
206+
args: tuple,
207+
kwargs: dict[str, _t.Any],
208+
) -> _t.Generator[None, None, None]:
209+
try:
210+
yield
211+
except TypeError:
212+
signature = _inspect.signature(setter)
213+
try:
214+
signature.bind(data, *args, **kwargs)
215+
except TypeError as bind_error:
216+
type_name_module = type(data).__module__
217+
if type_name_module == "builtins":
218+
type_name = type(data).__qualname__
219+
else:
220+
type_name = f"{type_name_module}.{type(data).__qualname__}"
221+
raise TypeError(
222+
"Invalid arguments for Vector initialization with "
223+
f"data of type {type_name}: {bind_error}"
224+
) from None
225+
raise
186226

187227
def raw(self, /, *, byteorder: _T_VectorEndian = "big") -> bytes:
188228
"""

0 commit comments

Comments
 (0)