File tree 3 files changed +12
-2
lines changed
3 files changed +12
-2
lines changed Original file line number Diff line number Diff line change @@ -904,7 +904,7 @@ class str : public object {
904
904
Return a string representation of the object. This is analogous to
905
905
the ``str()`` function in Python.
906
906
\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 (); }
908
908
909
909
operator std::string () const {
910
910
object temp = *this ;
@@ -929,8 +929,8 @@ class str : public object {
929
929
// / Return string representation -- always returns a new reference, even if already a str
930
930
static PyObject *raw_str (PyObject *op) {
931
931
PyObject *str_value = PyObject_Str (op);
932
- if (!str_value) throw error_already_set ();
933
932
#if PY_MAJOR_VERSION < 3
933
+ if (!str_value) throw error_already_set ();
934
934
PyObject *unicode = PyUnicode_FromEncodedObject (str_value, " utf-8" , nullptr );
935
935
Py_XDECREF (str_value); str_value = unicode;
936
936
#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 @@ -102,11 +102,20 @@ def __repr__(self):
102
102
103
103
assert m .str_from_object (A ()) == "this is a str"
104
104
assert m .repr_from_object (A ()) == "this is a repr"
105
+ assert m .str_from_handle (A ()) == "this is a str"
105
106
106
107
s1 , s2 = m .str_format ()
107
108
assert s1 == "1 + 2 = 3"
108
109
assert s1 == s2
109
110
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
+
110
119
111
120
def test_bytes (doc ):
112
121
assert m .bytes_from_string ().decode () == "foo"
You can’t perform that action at this time.
0 commit comments