File tree 3 files changed +15
-2
lines changed 3 files changed +15
-2
lines changed Original file line number Diff line number Diff line change @@ -920,7 +920,7 @@ class str : public object {
920
920
Return a string representation of the object. This is analogous to
921
921
the ``str()`` function in Python.
922
922
\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 (); }
924
924
925
925
operator std::string () const {
926
926
object temp = *this ;
@@ -945,8 +945,8 @@ class str : public object {
945
945
// / Return string representation -- always returns a new reference, even if already a str
946
946
static PyObject *raw_str (PyObject *op) {
947
947
PyObject *str_value = PyObject_Str (op);
948
- if (!str_value) throw error_already_set ();
949
948
#if PY_MAJOR_VERSION < 3
949
+ if (!str_value) throw error_already_set ();
950
950
PyObject *unicode = PyUnicode_FromEncodedObject (str_value, " utf-8" , nullptr );
951
951
Py_XDECREF (str_value); str_value = unicode;
952
952
#endif
Original file line number Diff line number Diff line change @@ -80,6 +80,7 @@ TEST_SUBMODULE(pytypes, m) {
80
80
m.def (" str_from_bytes" , []() { return py::str (py::bytes (" boo" , 3 )); });
81
81
m.def (" str_from_object" , [](const py::object& obj) { return py::str (obj); });
82
82
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); });
83
84
84
85
m.def (" str_format" , []() {
85
86
auto s1 = " {} + {} = {}" _s.format (1 , 2 , 3 );
Original file line number Diff line number Diff line change @@ -104,11 +104,23 @@ def __repr__(self):
104
104
105
105
assert m .str_from_object (A ()) == "this is a str"
106
106
assert m .repr_from_object (A ()) == "this is a repr"
107
+ assert m .str_from_handle (A ()) == "this is a str"
107
108
108
109
s1 , s2 = m .str_format ()
109
110
assert s1 == "1 + 2 = 3"
110
111
assert s1 == s2
111
112
113
+ malformed_utf8 = b"\x80 "
114
+ assert m .str_from_object (malformed_utf8 ) is malformed_utf8 # To be fixed; see #2380
115
+ if env .PY2 :
116
+ # with pytest.raises(UnicodeDecodeError):
117
+ # m.str_from_object(malformed_utf8)
118
+ with pytest .raises (UnicodeDecodeError ):
119
+ m .str_from_handle (malformed_utf8 )
120
+ else :
121
+ # assert m.str_from_object(malformed_utf8) == "b'\\x80'"
122
+ assert m .str_from_handle (malformed_utf8 ) == "b'\\ x80'"
123
+
112
124
113
125
def test_bytes (doc ):
114
126
assert m .bytes_from_string ().decode () == "foo"
You can’t perform that action at this time.
0 commit comments