Skip to content

Commit

Permalink
Use PyUnicodeWriter instead of string concatenation
Browse files Browse the repository at this point in the history
  • Loading branch information
tomasr8 committed Jul 11, 2024
1 parent cfd6cdf commit f022378
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 26 deletions.
27 changes: 14 additions & 13 deletions Parser/asdl_c.py
Original file line number Diff line number Diff line change
Expand Up @@ -1274,7 +1274,11 @@ def visitModule(self, mod):
return PyUnicode_FromFormat("%s()", Py_TYPE(self)->tp_name);
}
PyObject *repr = NULL;
const char* tp_name = Py_TYPE(self)->tp_name;
_PyUnicodeWriter writer;
_PyUnicodeWriter_Init(&writer);
_PyUnicodeWriter_WriteASCIIString(&writer, tp_name, strlen(tp_name));
_PyUnicodeWriter_WriteChar(&writer, '(');
for (Py_ssize_t i = 0; i < numfields; i++) {
PyObject *name = PySequence_GetItem(fields, i);
if (!name) {
Expand Down Expand Up @@ -1302,29 +1306,26 @@ def visitModule(self, mod):
goto error;
}
if (i == 0) {
repr = PyUnicode_FromFormat("%U=%U", name, value_repr);
} else {
PyObject *prev_repr = repr;
PyObject *tmp = PyUnicode_FromFormat(", %U=%U", name, value_repr);
repr = PyUnicode_Concat(prev_repr, tmp);
Py_DECREF(prev_repr);
Py_DECREF(tmp);
if (i > 0) {
_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2);
}
_PyUnicodeWriter_WriteStr(&writer, name);
_PyUnicodeWriter_WriteChar(&writer, '=');
_PyUnicodeWriter_WriteStr(&writer, value_repr);
Py_DECREF(name);
Py_DECREF(value);
Py_DECREF(value_repr);
}
_PyUnicodeWriter_WriteChar(&writer, ')');
Py_ReprLeave((PyObject *)self);
Py_DECREF(fields);
PyObject *ret = PyUnicode_FromFormat("%s(%U)", Py_TYPE(self)->tp_name, repr);
Py_DECREF(repr);
return ret;
return _PyUnicodeWriter_Finish(&writer);
error:
Py_ReprLeave((PyObject *)self);
Py_DECREF(fields);
_PyUnicodeWriter_Dealloc(&writer);
return NULL;
}
Expand Down
27 changes: 14 additions & 13 deletions Python/Python-ast.c

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit f022378

Please sign in to comment.