Skip to content

Commit bd8f366

Browse files
YannickJadoulrwgk
authored andcommitted
Add check if str(handle) correctly converted the object, and throw py::error_already_set if not
1 parent a48976f commit bd8f366

File tree

3 files changed

+12
-2
lines changed

3 files changed

+12
-2
lines changed

include/pybind11/pytypes.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -918,7 +918,7 @@ class str : public object {
918918
Return a string representation of the object. This is analogous to
919919
the ``str()`` function in Python.
920920
\endrst */
921-
explicit str(handle h) : object(raw_str(h.ptr()), stolen_t{}) { }
921+
explicit str(handle h) : object(raw_str(h.ptr()), stolen_t{}) { if (!m_ptr) throw error_already_set(); }
922922

923923
operator std::string() const {
924924
object temp = *this;
@@ -943,8 +943,8 @@ class str : public object {
943943
/// Return string representation -- always returns a new reference, even if already a str
944944
static PyObject *raw_str(PyObject *op) {
945945
PyObject *str_value = PyObject_Str(op);
946-
if (!str_value) throw error_already_set();
947946
#if PY_MAJOR_VERSION < 3
947+
if (!str_value) throw error_already_set();
948948
PyObject *unicode = PyUnicode_FromEncodedObject(str_value, "utf-8", nullptr);
949949
Py_XDECREF(str_value); str_value = unicode;
950950
#endif

tests/test_pytypes.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ TEST_SUBMODULE(pytypes, m) {
8080
m.def("str_from_bytes", []() { return py::str(py::bytes("boo", 3)); });
8181
m.def("str_from_object", [](const py::object& obj) { return py::str(obj); });
8282
m.def("repr_from_object", [](const py::object& obj) { return py::repr(obj); });
83+
m.def("str_from_handle", [](py::handle h) { return py::str(h); });
8384

8485
m.def("str_format", []() {
8586
auto s1 = "{} + {} = {}"_s.format(1, 2, 3);

tests/test_pytypes.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,11 +104,20 @@ def __repr__(self):
104104

105105
assert m.str_from_object(A()) == "this is a str"
106106
assert m.repr_from_object(A()) == "this is a repr"
107+
assert m.str_from_handle(A()) == "this is a str"
107108

108109
s1, s2 = m.str_format()
109110
assert s1 == "1 + 2 = 3"
110111
assert s1 == s2
111112

113+
malformed_utf8 = b"\x80"
114+
with pytest.raises(UnicodeDecodeError) as excinfo:
115+
assert m.str_from_object(malformed_utf8)
116+
assert 'invalid start byte' in str(excinfo.value)
117+
with pytest.raises(UnicodeDecodeError) as excinfo:
118+
assert m.str_from_handle(malformed_utf8)
119+
assert 'invalid start byte' in str(excinfo.value)
120+
112121

113122
def test_bytes(doc):
114123
assert m.bytes_from_string().decode() == "foo"

0 commit comments

Comments
 (0)