Skip to content

Commit cca4c51

Browse files
authored
Update errors in string "Explicit conversions" docs (#4658)
`PyUnicode_DecodeLatin1` requires you to pass in the `error` parameter. The code as it is in the docs didn't compile. There is a reference leak in the example code. `PyUnicode_DecodeLatin1` returns a new reference. Calling `py::str(PyObject*)` calls `PyObject_Str`, which also returns a new reference. That reference is managed by the `py::str` constructor (which correctly steals the reference, using the `stolen_t` constructor), but the original reference returned by `PyUnicode_DecodeLatin1` is never decref'd: it never makes it into an `object`, and it's never manually decremented. This fixes both of those issues. The code compiles, and I viewed the sphinx docs locally.
1 parent e9b961d commit cca4c51

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

docs/advanced/cast/strings.rst

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -101,8 +101,11 @@ conversion has the same overhead as implicit conversion.
101101
m.def("str_output",
102102
[]() {
103103
std::string s = "Send your r\xe9sum\xe9 to Alice in HR"; // Latin-1
104-
py::str py_s = PyUnicode_DecodeLatin1(s.data(), s.length());
105-
return py_s;
104+
py::handle py_s = PyUnicode_DecodeLatin1(s.data(), s.length(), nullptr);
105+
if (!py_s) {
106+
throw py::error_already_set();
107+
}
108+
return py::reinterpret_steal<py::str>(py_s);
106109
}
107110
);
108111

@@ -113,7 +116,8 @@ conversion has the same overhead as implicit conversion.
113116
114117
The `Python C API
115118
<https://docs.python.org/3/c-api/unicode.html#built-in-codecs>`_ provides
116-
several built-in codecs.
119+
several built-in codecs. Note that these all return *new* references, so
120+
use :cpp:func:`reinterpret_steal` when converting them to a :cpp:class:`str`.
117121

118122

119123
One could also use a third party encoding library such as libiconv to transcode

0 commit comments

Comments
 (0)