Skip to content

Commit d2418f0

Browse files
committed
Add func_is_stateless_with_exact_type feature in pybind11/functional.h
1 parent f02517e commit d2418f0

File tree

3 files changed

+14
-3
lines changed

3 files changed

+14
-3
lines changed

include/pybind11/functional.h

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
#pragma once
1111

12+
#define PYBIND11_HAS_TYPE_CASTER_STD_FUNCTION_FUNC_IS_STATELESS_WITH_EXACT_TYPE
1213
#define PYBIND11_HAS_TYPE_CASTER_STD_FUNCTION_SPECIALIZATIONS
1314

1415
#include "pybind11.h"
@@ -65,8 +66,15 @@ struct type_caster<std::function<Return(Args...)>> {
6566
using retval_type = conditional_t<std::is_same<Return, void>::value, void_type, Return>;
6667
using function_type = Return (*)(Args...);
6768

69+
private:
70+
bool func_is_stateless_with_exact_type_ = false;
71+
6872
public:
73+
bool func_is_stateless_with_exact_type() const { return func_is_stateless_with_exact_type_; }
74+
6975
bool load(handle src, bool convert) {
76+
func_is_stateless_with_exact_type_ = false;
77+
7078
if (src.is_none()) {
7179
// Defer accepting None to other overloads (if we aren't in convert mode):
7280
if (!convert) {
@@ -110,6 +118,7 @@ struct type_caster<std::function<Return(Args...)>> {
110118
function_type f;
111119
};
112120
value = ((capture *) &rec->data)->f;
121+
func_is_stateless_with_exact_type_ = true;
113122
return true;
114123
}
115124
rec = rec->next;

tests/test_callbacks.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,9 @@ double apply_custom_transform(const py::object &src, double value) {
2929
if (!func_caster.load(src, /*convert*/ false)) {
3030
return -100;
3131
}
32+
if (!func_caster.func_is_stateless_with_exact_type()) {
33+
return -200;
34+
}
3235
return static_cast<std::function<raw_t> &>(func_caster)(value);
3336
}
3437

tests/test_callbacks.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -241,9 +241,8 @@ def test_boost_histogram_apply_custom_transform():
241241
cti = m.boost_histogram_custom_transform_int
242242
apply = m.boost_histogram_apply_custom_transform
243243
assert apply(ctd, 5) == 15
244-
with pytest.raises(TypeError):
245-
assert apply(cti, 0)
244+
assert apply(cti, 0) == -200
246245
assert apply(None, 0) == -100
247-
assert apply(lambda value: value * 10, 4) == 40
246+
assert apply(lambda value: value, 9) == -200
248247
assert apply({}, 0) == -100
249248
assert apply("", 0) == -100

0 commit comments

Comments
 (0)