Skip to content

Commit d629d5e

Browse files
committed
Adds check if str(handle) correctly converted the object, and throw py::error_already_set if not.
Similar to pybind#2392, but does not depend on pybind#2409. Splitting out this PR from pybind#2409 to make that PR as simple as possible. Net effects of this PR: * Adds missing test coverage. * Changes TypeError to UnicodeDecodeError for Python 2. This PR has two commits. Please do not squash, to make the behavior change obvious in the commit history.
1 parent 44b3941 commit d629d5e

File tree

2 files changed

+3
-3
lines changed

2 files changed

+3
-3
lines changed

include/pybind11/pytypes.h

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

925925
operator std::string() const {
926926
object temp = *this;
@@ -945,8 +945,8 @@ class str : public object {
945945
/// Return string representation -- always returns a new reference, even if already a str
946946
static PyObject *raw_str(PyObject *op) {
947947
PyObject *str_value = PyObject_Str(op);
948-
if (!str_value) throw error_already_set();
949948
#if PY_MAJOR_VERSION < 3
949+
if (!str_value) throw error_already_set();
950950
PyObject *unicode = PyUnicode_FromEncodedObject(str_value, "utf-8", nullptr);
951951
Py_XDECREF(str_value); str_value = unicode;
952952
#endif

tests/test_pytypes.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ def __repr__(self):
114114
malformed_utf8 = b"\x80"
115115
assert m.str_from_object(malformed_utf8) is malformed_utf8 # Probably surprising.
116116
if env.PY2:
117-
with pytest.raises(TypeError):
117+
with pytest.raises(UnicodeDecodeError):
118118
m.str_from_handle(malformed_utf8)
119119
else:
120120
assert m.str_from_handle(malformed_utf8) == "b'\\x80'"

0 commit comments

Comments
 (0)