Skip to content

Commit c60b3b3

Browse files
authored
gh-98421: Clean Up PyObject_Print (GH-98422)
Work on test coverage for `PyObject_Print` made it clear that some lines can't get executed. Simplify the function by excluding the checks for non-string types. Also eliminate creating a temporary bytes object.
1 parent e48f9b2 commit c60b3b3

File tree

1 file changed

+8
-17
lines changed

1 file changed

+8
-17
lines changed

Objects/object.c

+8-17
Original file line numberDiff line numberDiff line change
@@ -282,31 +282,22 @@ PyObject_Print(PyObject *op, FILE *fp, int flags)
282282
s = PyObject_Str(op);
283283
else
284284
s = PyObject_Repr(op);
285-
if (s == NULL)
285+
if (s == NULL) {
286286
ret = -1;
287-
else if (PyBytes_Check(s)) {
288-
fwrite(PyBytes_AS_STRING(s), 1,
289-
PyBytes_GET_SIZE(s), fp);
290287
}
291-
else if (PyUnicode_Check(s)) {
292-
PyObject *t;
293-
t = PyUnicode_AsEncodedString(s, "utf-8", "backslashreplace");
288+
else {
289+
assert(PyUnicode_Check(s));
290+
const char *t;
291+
Py_ssize_t len;
292+
t = PyUnicode_AsUTF8AndSize(s, &len);
294293
if (t == NULL) {
295294
ret = -1;
296295
}
297296
else {
298-
fwrite(PyBytes_AS_STRING(t), 1,
299-
PyBytes_GET_SIZE(t), fp);
300-
Py_DECREF(t);
297+
fwrite(t, 1, len, fp);
301298
}
299+
Py_DECREF(s);
302300
}
303-
else {
304-
PyErr_Format(PyExc_TypeError,
305-
"str() or repr() returned '%.100s'",
306-
Py_TYPE(s)->tp_name);
307-
ret = -1;
308-
}
309-
Py_XDECREF(s);
310301
}
311302
}
312303
if (ret == 0) {

0 commit comments

Comments
 (0)