Skip to content

Commit e9b961d

Browse files
authored
Elide to-python conversion of setter return values (#4621)
* Reproducer for property setter with return type that is not wrapped. * Use `py::class_<OptionsBase>()` to work around the return value conversion issue. * WIP drop_return_value * Remove struct drop_return_value * Introduce `return_value_policy::return_none` for use by setters. * Add `is_setter` to attr.h and use from `.def_property()` * Merge the new test into test_methods_and_attributes * Remove return_none return_value_policy again. * Fix oversight (NOLINTNEXTLINE placement). * Simplification (for the better) found while searching for a way to resolve GCC build failures. Example of failure resolved by this change: g++ (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0 ``` cd /build/tests && /usr/bin/c++ -DPYBIND11_TEST_EIGEN -Dpybind11_tests_EXPORTS -I/mounted_pybind11/include -isystem /usr/include/python3.8 -isystem /build/_deps/eigen-src -g -std=c++17 -fPIC -fvisibility=hidden -Wall -Wextra -Wconversion -Wcast-qual -Wdeprecated -Wundef -Wnon-virtual-dtor -MD -MT tests/CMakeFiles/pybind11_tests.dir/test_buffers.cpp.o -MF CMakeFiles/pybind11_tests.dir/test_buffers.cpp.o.d -o CMakeFiles/pybind11_tests.dir/test_buffers.cpp.o -c /mounted_pybind11/tests/test_buffers.cpp In file included from /mounted_pybind11/include/pybind11/stl.h:12, from /mounted_pybind11/tests/test_buffers.cpp:10: /mounted_pybind11/include/pybind11/pybind11.h: In instantiation of ‘pybind11::class_<type_, options>& pybind11::class_<type_, options>::def_property(const char*, const Getter&, const Setter&, const Extra& ...) [with Getter = pybind11::cpp_function; Setter = std::nullptr_t; Extra = {pybind11::return_value_policy}; type_ = pybind11::buffer_info; options = {}]’: /mounted_pybind11/include/pybind11/pybind11.h:1716:58: required from ‘pybind11::class_<type_, options>& pybind11::class_<type_, options>::def_property_readonly(const char*, const pybind11::cpp_function&, const Extra& ...) [with Extra = {pybind11::return_value_policy}; type_ = pybind11::buffer_info; options = {}]’ /mounted_pybind11/include/pybind11/pybind11.h:1684:9: required from ‘pybind11::class_<type_, options>& pybind11::class_<type_, options>::def_readonly(const char*, const D C::*, const Extra& ...) [with C = pybind11::buffer_info; D = long int; Extra = {}; type_ = pybind11::buffer_info; options = {}]’ /mounted_pybind11/tests/test_buffers.cpp:209:61: required from here /mounted_pybind11/include/pybind11/pybind11.h:1740:25: error: call of overloaded ‘cpp_function(std::nullptr_t&, pybind11::is_setter)’ is ambiguous 1740 | name, fget, cpp_function(method_adaptor<type>(fset), is_setter()), extra...); | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /mounted_pybind11/include/pybind11/pybind11.h:101:5: note: candidate: ‘pybind11::cpp_function::cpp_function(Func&&, const Extra& ...) [with Func = std::nullptr_t&; Extra = {pybind11::is_setter}; <template-parameter-1-3> = void]’ 101 | cpp_function(Func &&f, const Extra &...extra) { | ^~~~~~~~~~~~ In file included from /mounted_pybind11/include/pybind11/stl.h:12, from /mounted_pybind11/tests/test_buffers.cpp:10: /mounted_pybind11/include/pybind11/pybind11.h:87:5: note: candidate: ‘pybind11::cpp_function::cpp_function(std::nullptr_t, const Extra& ...) [with Extra = {pybind11::is_setter}; std::nullptr_t = std::nullptr_t]’ 87 | cpp_function(std::nullptr_t, const Extra &...) {} | ^~~~~~~~~~~~ ``` * Bug fix: obvious in hindsight. I thought the original version was incrementing the reference count for None, but no. Discovered via many failing tests in the wild (10s of thousands). It is very tricky to construct a meaningful unit test for this bug specifically. It's unlikely to come back, because 10s of thousands of tests will fail again.
1 parent 90312a6 commit e9b961d

File tree

4 files changed

+70
-7
lines changed

4 files changed

+70
-7
lines changed

include/pybind11/attr.h

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,9 @@ struct is_method {
2626
explicit is_method(const handle &c) : class_(c) {}
2727
};
2828

29+
/// Annotation for setters
30+
struct is_setter {};
31+
2932
/// Annotation for operators
3033
struct is_operator {};
3134

@@ -188,8 +191,8 @@ struct argument_record {
188191
struct function_record {
189192
function_record()
190193
: is_constructor(false), is_new_style_constructor(false), is_stateless(false),
191-
is_operator(false), is_method(false), has_args(false), has_kwargs(false),
192-
prepend(false) {}
194+
is_operator(false), is_method(false), is_setter(false), has_args(false),
195+
has_kwargs(false), prepend(false) {}
193196

194197
/// Function name
195198
char *name = nullptr; /* why no C++ strings? They generate heavier code.. */
@@ -230,6 +233,9 @@ struct function_record {
230233
/// True if this is a method
231234
bool is_method : 1;
232235

236+
/// True if this is a setter
237+
bool is_setter : 1;
238+
233239
/// True if the function has a '*args' argument
234240
bool has_args : 1;
235241

@@ -426,6 +432,12 @@ struct process_attribute<is_method> : process_attribute_default<is_method> {
426432
}
427433
};
428434

435+
/// Process an attribute which indicates that this function is a setter
436+
template <>
437+
struct process_attribute<is_setter> : process_attribute_default<is_setter> {
438+
static void init(const is_setter &, function_record *r) { r->is_setter = true; }
439+
};
440+
429441
/// Process an attribute which indicates the parent scope of a method
430442
template <>
431443
struct process_attribute<scope> : process_attribute_default<scope> {

include/pybind11/pybind11.h

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ class cpp_function : public function {
8484
cpp_function() = default;
8585
// NOLINTNEXTLINE(google-explicit-constructor)
8686
cpp_function(std::nullptr_t) {}
87+
cpp_function(std::nullptr_t, const is_setter &) {}
8788

8889
/// Construct a cpp_function from a vanilla function pointer
8990
template <typename Return, typename... Args, typename... Extra>
@@ -244,10 +245,16 @@ class cpp_function : public function {
244245
using Guard = extract_guard_t<Extra...>;
245246

246247
/* Perform the function call */
247-
handle result
248-
= cast_out::cast(std::move(args_converter).template call<Return, Guard>(cap->f),
249-
policy,
250-
call.parent);
248+
handle result;
249+
if (call.func.is_setter) {
250+
(void) std::move(args_converter).template call<Return, Guard>(cap->f);
251+
result = none().release();
252+
} else {
253+
result = cast_out::cast(
254+
std::move(args_converter).template call<Return, Guard>(cap->f),
255+
policy,
256+
call.parent);
257+
}
251258

252259
/* Invoke call policy post-call hook */
253260
process_attributes<Extra...>::postcall(call, result);
@@ -1729,7 +1736,8 @@ class class_ : public detail::generic_type {
17291736
template <typename Getter, typename Setter, typename... Extra>
17301737
class_ &
17311738
def_property(const char *name, const Getter &fget, const Setter &fset, const Extra &...extra) {
1732-
return def_property(name, fget, cpp_function(method_adaptor<type>(fset)), extra...);
1739+
return def_property(
1740+
name, fget, cpp_function(method_adaptor<type>(fset), is_setter()), extra...);
17331741
}
17341742
template <typename Getter, typename... Extra>
17351743
class_ &def_property(const char *name,

tests/test_methods_and_attributes.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,38 @@ struct RValueRefParam {
177177
std::size_t func4(std::string &&s) const & { return s.size(); }
178178
};
179179

180+
namespace pybind11_tests {
181+
namespace exercise_is_setter {
182+
183+
struct FieldBase {
184+
int int_value() const { return int_value_; }
185+
186+
FieldBase &SetIntValue(int int_value) {
187+
int_value_ = int_value;
188+
return *this;
189+
}
190+
191+
private:
192+
int int_value_ = -99;
193+
};
194+
195+
struct Field : FieldBase {};
196+
197+
void add_bindings(py::module &m) {
198+
py::module sm = m.def_submodule("exercise_is_setter");
199+
// NOTE: FieldBase is not wrapped, therefore ...
200+
py::class_<Field>(sm, "Field")
201+
.def(py::init<>())
202+
.def_property(
203+
"int_value",
204+
&Field::int_value,
205+
&Field::SetIntValue // ... the `FieldBase &` return value here cannot be converted.
206+
);
207+
}
208+
209+
} // namespace exercise_is_setter
210+
} // namespace pybind11_tests
211+
180212
TEST_SUBMODULE(methods_and_attributes, m) {
181213
// test_methods_and_attributes
182214
py::class_<ExampleMandA> emna(m, "ExampleMandA");
@@ -456,4 +488,6 @@ TEST_SUBMODULE(methods_and_attributes, m) {
456488
.def("func2", &RValueRefParam::func2)
457489
.def("func3", &RValueRefParam::func3)
458490
.def("func4", &RValueRefParam::func4);
491+
492+
pybind11_tests::exercise_is_setter::add_bindings(m);
459493
}

tests/test_methods_and_attributes.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -522,3 +522,12 @@ def test_rvalue_ref_param():
522522
assert r.func2("1234") == 4
523523
assert r.func3("12345") == 5
524524
assert r.func4("123456") == 6
525+
526+
527+
def test_is_setter():
528+
fld = m.exercise_is_setter.Field()
529+
assert fld.int_value == -99
530+
setter_return = fld.int_value = 100
531+
assert isinstance(setter_return, int)
532+
assert setter_return == 100
533+
assert fld.int_value == 100

0 commit comments

Comments
 (0)