Fix #283: don't print first arg of constructor
This changes the exception error message of a bad-arguments error to
suppress the constructor argument when the failure is a constructor.
This changes both the "Invoked with: " output to omit the object
instances, and rewrites the constructor signature to make it look
like a constructor (changing the first argument to the object name, and
removing the ' -> NoneType' return type.
diff --git a/example/issues.cpp b/example/issues.cpp
index 8314759..55fc3f3 100644
--- a/example/issues.cpp
+++ b/example/issues.cpp
@@ -138,4 +138,23 @@
} catch (std::runtime_error &) {
/* All good */
}
+
+ // Issue #283: __str__ called on uninitialized instance when constructor arguments invalid
+ class StrIssue {
+ public:
+ StrIssue(int i) : val{i} {}
+ StrIssue() : StrIssue(-1) {}
+ int value() const { return val; }
+ private:
+ int val;
+ };
+ py::class_<StrIssue> si(m2, "StrIssue");
+ si .def(py::init<int>())
+ .def(py::init<>())
+ .def("__str__", [](const StrIssue &si) {
+ std::cout << "StrIssue.__str__ called" << std::endl;
+ return "StrIssue[" + std::to_string(si.value()) + "]";
+ })
+ ;
+
}
diff --git a/example/issues.py b/example/issues.py
index 257f08e..716a1b2 100644
--- a/example/issues.py
+++ b/example/issues.py
@@ -10,6 +10,7 @@
from example.issues import ElementList, ElementA, print_element
from example.issues import expect_float, expect_int
from example.issues import A, call_f
+from example.issues import StrIssue
import gc
print_cchar("const char *")
@@ -72,3 +73,8 @@
b = B()
call_f(b)
+print(StrIssue(3))
+try:
+ print(StrIssue("no", "such", "constructor"))
+except TypeError as e:
+ print("Failed as expected: " + str(e))
diff --git a/example/issues.ref b/example/issues.ref
index 58cc798..0386d2c 100644
--- a/example/issues.ref
+++ b/example/issues.ref
@@ -18,3 +18,9 @@
PyA.PyA()
PyA.f()
In python f()
+StrIssue.__str__ called
+StrIssue[3]
+Failed as expected: Incompatible constructor arguments. The following argument types are supported:
+ 1. example.issues.StrIssue(int)
+ 2. example.issues.StrIssue()
+ Invoked with: no, such, constructor