Skip to content

Commit 2d4a04b

Browse files
committed
Avoid attr("__repr__") in initialize_generic
If the default argument value is a class, and not an instance of a class, `a.value.attr("__repr__")` raises a `ValueError`. Switching to `repr(a.value)` makes this use case work. Fixes #2028
1 parent 6f3e5e3 commit 2d4a04b

File tree

3 files changed

+8
-1
lines changed

3 files changed

+8
-1
lines changed

include/pybind11/pybind11.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,7 @@ class cpp_function : public function {
228228
if (a.descr)
229229
a.descr = strdup(a.descr);
230230
else if (a.value)
231-
a.descr = strdup(a.value.attr("__repr__")().cast<std::string>().c_str());
231+
a.descr = strdup(repr(a.value).cast<std::string>().c_str());
232232
}
233233

234234
rec->is_constructor = !strcmp(rec->name, "__init__") || !strcmp(rec->name, "__setstate__");

tests/test_kwargs_and_defaults.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,4 +123,9 @@ TEST_SUBMODULE(kwargs_and_defaults, m) {
123123
py::class_<KWClass>(m, "KWClass")
124124
.def("foo0", &KWClass::foo)
125125
.def("foo1", &KWClass::foo, "x"_a, "y"_a);
126+
127+
// Make sure a class (not an instance) can be used as a default argument.
128+
// The return value doesn't matter, only that the module is importable.
129+
m.def("class_default_argument", [](py::object a) { return py::repr(a); },
130+
"a"_a = py::module::import("decimal").attr("Decimal"));
126131
}

tests/test_kwargs_and_defaults.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,3 +191,5 @@ def test_args_refcount():
191191
# tuple without having to inc_ref the individual elements, but here we can't, hence the extra
192192
# refs.
193193
assert m.mixed_args_refcount(myval, myval, myval) == (exp3 + 3, exp3 + 3, exp3 + 3)
194+
195+
assert m.class_default_argument() == "<class 'decimal.Decimal'>"

0 commit comments

Comments
 (0)