Skip to content

Commit 6c44020

Browse files
committed
Fixed on PyPy
1 parent 4d8024f commit 6c44020

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

include/pybind11/cast.h

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1020,23 +1020,32 @@ struct type_caster<T, enable_if_t<std::is_arithmetic<T>::value && !is_std_char_t
10201020
if (!src)
10211021
return false;
10221022

1023+
#if !defined(PYPY_VERSION)
1024+
auto index_check = [](PyObject *o) { return PyIndex_Check(o); };
1025+
#else
1026+
// In PyPy 7.3.3, `PyIndex_Check` is implemented by calling `__index__`,
1027+
// while CPython only considers the existence of `nb_index`/`__index__`.
1028+
auto index_check = [](PyObject *o) { return hasattr(o, "__index__"); };
1029+
#endif
1030+
10231031
if (std::is_floating_point<T>::value) {
10241032
if (convert || PyFloat_Check(src.ptr()))
10251033
py_value = (py_type) PyFloat_AsDouble(src.ptr());
10261034
else
10271035
return false;
10281036
} else if (PyFloat_Check(src.ptr())) {
10291037
return false;
1030-
} else if (!convert && !PyIndex_Check(src.ptr()) && !PYBIND11_LONG_CHECK(src.ptr())) {
1038+
} else if (!convert && !index_check(src.ptr()) && !PYBIND11_LONG_CHECK(src.ptr())) {
10311039
return false;
10321040
} else {
10331041
handle obj = src;
10341042
#if PY_VERSION_HEX < 0x03080000
10351043
bool do_decref = false;
1036-
if (PyIndex_Check(src.ptr())) {
1044+
if (index_check(src.ptr())) {
10371045
PyObject *tmp = PyNumber_Index(src.ptr());
10381046
if (!tmp) {
1039-
py_value = (py_type) -1;
1047+
PyErr_Clear();
1048+
return false;
10401049
}
10411050
do_decref = true;
10421051
obj = tmp;

0 commit comments

Comments
 (0)