Skip to content

Commit d58307d

Browse files
committed
Add check if str(handle) correctly converted the object, and throw py::error_already_set if not
1 parent fb6bb7e commit d58307d

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
@@ -904,7 +904,7 @@ class str : public object {
904904
Return a string representation of the object. This is analogous to
905905
the ``str()`` function in Python.
906906
\endrst */
907-
explicit str(handle h) : object(raw_str(h.ptr()), stolen_t{}) { }
907+
explicit str(handle h) : object(raw_str(h.ptr()), stolen_t{}) { if (!m_ptr) throw error_already_set(); }
908908

909909
operator std::string() const {
910910
object temp = *this;
@@ -929,8 +929,8 @@ class str : public object {
929929
/// Return string representation -- always returns a new reference, even if already a str
930930
static PyObject *raw_str(PyObject *op) {
931931
PyObject *str_value = PyObject_Str(op);
932-
if (!str_value) throw error_already_set();
933932
#if PY_MAJOR_VERSION < 3
933+
if (!str_value) throw error_already_set();
934934
PyObject *unicode = PyUnicode_FromEncodedObject(str_value, "utf-8", nullptr);
935935
Py_XDECREF(str_value); str_value = unicode;
936936
#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
@@ -102,11 +102,20 @@ def __repr__(self):
102102

103103
assert m.str_from_object(A()) == "this is a str"
104104
assert m.repr_from_object(A()) == "this is a repr"
105+
assert m.str_from_handle(A()) == "this is a str"
105106

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

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

111120
def test_bytes(doc):
112121
assert m.bytes_from_string().decode() == "foo"

0 commit comments

Comments
 (0)