Skip to content

Commit f0fa0a2

Browse files
committed
gh-161934: Preallocate print output parts
1 parent d5def80 commit f0fa0a2

2 files changed

Lines changed: 10 additions & 1 deletion

File tree

‎Lib/test/test_print.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,8 @@ def test_print_single_write(self):
138138
(('a', 1, None), {}, 'a 1 None\n'),
139139
(('a', 'b'), {'sep': None, 'end': None}, 'a b\n'),
140140
(('a', 'b'), {'sep': '', 'end': ''}, 'ab'),
141+
(tuple(range(100)), {'sep': '|', 'end': '!'},
142+
'|'.join(map(str, range(100))) + '!'),
141143
(('a\0', '\u20ac', '\U0001f40d'),
142144
{'sep': '\u3000', 'end': '!'}, 'a\0\u3000\u20ac\u3000\U0001f40d!'),
143145
]

‎Python/bltinmodule.c‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2278,11 +2278,18 @@ builtin_print_impl(PyObject *module, PyObject * const *objects,
22782278
return NULL;
22792279
}
22802280

2281-
PyObject *parts = PyList_New(0);
2281+
if (objects_length > PY_SSIZE_T_MAX / 2) {
2282+
Py_DECREF(file);
2283+
return PyErr_NoMemory();
2284+
}
2285+
/* Reserve space for the arguments, separators, and terminator. */
2286+
PyObject *parts = PyList_New(Py_MAX(1, objects_length * 2));
22822287
if (parts == NULL) {
22832288
Py_DECREF(file);
22842289
return NULL;
22852290
}
2291+
/* Keep only accumulated parts visible when a conversion fails. */
2292+
Py_SET_SIZE(parts, 0);
22862293
PyObject *exception, *saved_exception, *line;
22872294
for (Py_ssize_t i = 0; i < objects_length; i++) {
22882295
if (i > 0 && PyList_Append(parts, sep) < 0) {

0 commit comments

Comments
 (0)