Skip to content

Commit

Permalink
Simplify use of PyNumber_Index, following @rwgk's idea, and ignore wa…
Browse files Browse the repository at this point in the history
…rnings in >=3.8
  • Loading branch information
YannickJadoul committed Jan 20, 2021
1 parent 2eb35ac commit 064d671
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 13 deletions.
21 changes: 8 additions & 13 deletions include/pybind11/cast.h
Original file line number Diff line number Diff line change
Expand Up @@ -1043,30 +1043,25 @@ struct type_caster<T, enable_if_t<std::is_arithmetic<T>::value && !is_std_char_t
} else if (!convert && !index_check(src.ptr()) && !PYBIND11_LONG_CHECK(src.ptr())) {
return false;
} else {
handle obj = src;
handle src_or_index = src;
#if PY_VERSION_HEX < 0x03080000
bool do_decref = false;
object index;
if (index_check(src.ptr())) {
PyObject *tmp = PyNumber_Index(src.ptr());
if (!tmp) {
index = reinterpret_steal<object>(PyNumber_Index(src.ptr()));
if (!index) {
PyErr_Clear();
return false;
}
do_decref = true;
obj = tmp;
src_or_index = index;
}
#endif
if (std::is_unsigned<py_type>::value) {
py_value = as_unsigned<py_type>(obj.ptr());
py_value = as_unsigned<py_type>(src_or_index.ptr());
} else { // signed integer:
py_value = sizeof(T) <= sizeof(long)
? (py_type) PyLong_AsLong(obj.ptr())
: (py_type) PYBIND11_LONG_AS_LONGLONG(obj.ptr());
? (py_type) PyLong_AsLong(src_or_index.ptr())
: (py_type) PYBIND11_LONG_AS_LONGLONG(src_or_index.ptr());
}
#if PY_VERSION_HEX < 0x03080000
if (do_decref)
obj.dec_ref();
#endif
}

// Python API reported an error
Expand Down
2 changes: 2 additions & 0 deletions tests/test_builtin_casters.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,7 @@ def test_integer_casting():
assert "incompatible function arguments" in str(excinfo.value)


@pytest.mark.filterwarnings("ignore:an integer is required:DeprecationWarning")
def test_int_convert():
class DeepThought(object):
def __int__(self):
Expand Down Expand Up @@ -297,6 +298,7 @@ def cant_convert(v):
cant_convert(RaisingThought()) # no fall-back to `__int__`if `__index__` raises


@pytest.mark.filterwarnings("ignore:an integer is required:DeprecationWarning")
def test_numpy_int_convert():
np = pytest.importorskip("numpy")

Expand Down

0 comments on commit 064d671

Please sign in to comment.