Skip to content

Commit fa2f884

Browse files
committed
use PyUnicodeWriter
1 parent 458bcd0 commit fa2f884

File tree

1 file changed

+24
-13
lines changed

1 file changed

+24
-13
lines changed

Objects/exceptions.c

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1870,24 +1870,35 @@ ImportError_repr(PyObject *self)
18701870
int hasargs = PyTuple_GET_SIZE(((PyBaseExceptionObject *)self)->args) != 0;
18711871
PyObject *r = BaseException_repr(self);
18721872
PyImportErrorObject *exc = PyImportErrorObject_CAST(self);
1873-
1873+
PyUnicodeWriter *writer = PyUnicodeWriter_Create(0);
1874+
if (writer == NULL) goto error;
1875+
if (PyUnicodeWriter_WriteSubstring(writer, r, 0, PyUnicode_GET_LENGTH(r)-1) < 0) goto error;
18741876
if (r && (exc->name || exc->path)) {
1875-
/* remove ')' */
1876-
Py_SETREF(r, PyUnicode_Substring(r, 0, PyUnicode_GET_LENGTH(r) - 1));
1877-
if (r && exc->name) {
1878-
Py_SETREF(r, PyUnicode_FromFormat("%U%sname=%R",
1879-
r, hasargs ? ", " : "", exc->name));
1877+
if (exc->name) {
1878+
if (hasargs) {
1879+
if (PyUnicodeWriter_WriteASCII(writer, ", ", 2) < 0) goto error;
1880+
}
1881+
if (PyUnicodeWriter_WriteASCII(writer, "name='", 6) < 0) goto error;
1882+
if (PyUnicodeWriter_WriteSubstring(writer, exc->name, 0, PyUnicode_GET_LENGTH(exc->name)) < 0) goto error;
1883+
if (PyUnicodeWriter_WriteASCII(writer, "'", 1) < 0) goto error;
18801884
hasargs = 1;
18811885
}
1882-
if (r && exc->path) {
1883-
Py_SETREF(r, PyUnicode_FromFormat("%U%spath=%R",
1884-
r, hasargs ? ", " : "", exc->path));
1885-
}
1886-
if (r) {
1887-
Py_SETREF(r, PyUnicode_FromFormat("%U)", r));
1886+
if (exc->path) {
1887+
if (hasargs) {
1888+
if (PyUnicodeWriter_WriteASCII(writer, ", ", 2) < 0) goto error;
1889+
}
1890+
if (PyUnicodeWriter_WriteASCII(writer, "path='", 6) < 0) goto error;
1891+
if (PyUnicodeWriter_WriteSubstring(writer, exc->path, 0, PyUnicode_GET_LENGTH(exc->path)) < 0) goto error;
1892+
if (PyUnicodeWriter_WriteASCII(writer, "'", 1) < 0) goto error;
18881893
}
18891894
}
1890-
return r;
1895+
if (PyUnicodeWriter_WriteASCII(writer, ")", 1) < 0) goto error;
1896+
return PyUnicodeWriter_Finish(writer);
1897+
1898+
error:
1899+
Py_XDECREF(r);
1900+
PyUnicodeWriter_Discard(writer);
1901+
return NULL;
18911902
}
18921903

18931904
static PyMemberDef ImportError_members[] = {

0 commit comments

Comments
 (0)