Skip to content

Commit 064d671

Browse files
committed
Simplify use of PyNumber_Index, following @rwgk's idea, and ignore warnings in >=3.8
1 parent 2eb35ac commit 064d671

File tree

2 files changed

+10
-13
lines changed

2 files changed

+10
-13
lines changed

include/pybind11/cast.h

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1043,30 +1043,25 @@ struct type_caster<T, enable_if_t<std::is_arithmetic<T>::value && !is_std_char_t
10431043
} else if (!convert && !index_check(src.ptr()) && !PYBIND11_LONG_CHECK(src.ptr())) {
10441044
return false;
10451045
} else {
1046-
handle obj = src;
1046+
handle src_or_index = src;
10471047
#if PY_VERSION_HEX < 0x03080000
1048-
bool do_decref = false;
1048+
object index;
10491049
if (index_check(src.ptr())) {
1050-
PyObject *tmp = PyNumber_Index(src.ptr());
1051-
if (!tmp) {
1050+
index = reinterpret_steal<object>(PyNumber_Index(src.ptr()));
1051+
if (!index) {
10521052
PyErr_Clear();
10531053
return false;
10541054
}
1055-
do_decref = true;
1056-
obj = tmp;
1055+
src_or_index = index;
10571056
}
10581057
#endif
10591058
if (std::is_unsigned<py_type>::value) {
1060-
py_value = as_unsigned<py_type>(obj.ptr());
1059+
py_value = as_unsigned<py_type>(src_or_index.ptr());
10611060
} else { // signed integer:
10621061
py_value = sizeof(T) <= sizeof(long)
1063-
? (py_type) PyLong_AsLong(obj.ptr())
1064-
: (py_type) PYBIND11_LONG_AS_LONGLONG(obj.ptr());
1062+
? (py_type) PyLong_AsLong(src_or_index.ptr())
1063+
: (py_type) PYBIND11_LONG_AS_LONGLONG(src_or_index.ptr());
10651064
}
1066-
#if PY_VERSION_HEX < 0x03080000
1067-
if (do_decref)
1068-
obj.dec_ref();
1069-
#endif
10701065
}
10711066

10721067
// Python API reported an error

tests/test_builtin_casters.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,7 @@ def test_integer_casting():
251251
assert "incompatible function arguments" in str(excinfo.value)
252252

253253

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

299300

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

0 commit comments

Comments
 (0)