Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds check if str(handle) correctly converted the object, and throw py::error_already_set if not. #2473

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions include/pybind11/pytypes.h
Original file line number Diff line number Diff line change
Expand Up @@ -920,7 +920,7 @@ class str : public object {
Return a string representation of the object. This is analogous to
the ``str()`` function in Python.
\endrst */
explicit str(handle h) : object(raw_str(h.ptr()), stolen_t{}) { }
explicit str(handle h) : object(raw_str(h.ptr()), stolen_t{}) { if (!m_ptr) throw error_already_set(); }

operator std::string() const {
object temp = *this;
Expand All @@ -945,8 +945,8 @@ class str : public object {
/// Return string representation -- always returns a new reference, even if already a str
static PyObject *raw_str(PyObject *op) {
PyObject *str_value = PyObject_Str(op);
if (!str_value) throw error_already_set();
#if PY_MAJOR_VERSION < 3
if (!str_value) throw error_already_set();
PyObject *unicode = PyUnicode_FromEncodedObject(str_value, "utf-8", nullptr);
Py_XDECREF(str_value); str_value = unicode;
#endif
Expand Down
1 change: 1 addition & 0 deletions tests/test_pytypes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ TEST_SUBMODULE(pytypes, m) {
m.def("str_from_bytes", []() { return py::str(py::bytes("boo", 3)); });
m.def("str_from_object", [](const py::object& obj) { return py::str(obj); });
m.def("repr_from_object", [](const py::object& obj) { return py::repr(obj); });
m.def("str_from_handle", [](py::handle h) { return py::str(h); });

m.def("str_format", []() {
auto s1 = "{} + {} = {}"_s.format(1, 2, 3);
Expand Down
10 changes: 10 additions & 0 deletions tests/test_pytypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,16 @@ def __repr__(self):
assert s1 == "1 + 2 = 3"
assert s1 == s2

assert m.str_from_handle(A()) == "this is a str"

malformed_utf8 = b"\x80"
assert m.str_from_object(malformed_utf8) is malformed_utf8 # Probably surprising.
if env.PY2:
with pytest.raises(UnicodeDecodeError):
m.str_from_handle(malformed_utf8)
else:
assert m.str_from_handle(malformed_utf8) == "b'\\x80'"


def test_bytes(doc):
assert m.bytes_from_string().decode() == "foo"
Expand Down