diff options
author | Victor Stinner <vstinner@python.org> | 2024-06-20 19:56:47 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2024-06-20 19:56:47 (GMT) |
commit | 56657f6be26c11e4b7045515fd3bd15bbda3c338 (patch) | |
tree | e95fed702533553c2c3ed75c19d5ff940ea61406 /Python/context.c | |
parent | 5150795b1cb6393e2b34834b2729d9176315054e (diff) | |
download | cpython-56657f6be26c11e4b7045515fd3bd15bbda3c338.zip cpython-56657f6be26c11e4b7045515fd3bd15bbda3c338.tar.gz cpython-56657f6be26c11e4b7045515fd3bd15bbda3c338.tar.bz2 |
gh-119182: Use public PyUnicodeWriter in contextvar_tp_repr() (#120809)
The public PyUnicodeWriter API enables overallocation by default and
so is more efficient. It also makes the code simpler and shorter.
Diffstat (limited to 'Python/context.c')
-rw-r--r-- | Python/context.c | 47 |
1 files changed, 15 insertions, 32 deletions
diff --git a/Python/context.c b/Python/context.c index 3937819..42000b1 100644 --- a/Python/context.c +++ b/Python/context.c @@ -893,56 +893,39 @@ contextvar_tp_hash(PyContextVar *self) static PyObject * contextvar_tp_repr(PyContextVar *self) { - _PyUnicodeWriter writer; - - _PyUnicodeWriter_Init(&writer); - - if (_PyUnicodeWriter_WriteASCIIString( - &writer, "<ContextVar name=", 17) < 0) - { - goto error; + // Estimation based on the shortest name and default value, + // but maximize the pointer size. + // "<ContextVar name='a' at 0x1234567812345678>" + // "<ContextVar name='a' default=1 at 0x1234567812345678>" + Py_ssize_t estimate = self->var_default ? 53 : 43; + PyUnicodeWriter *writer = PyUnicodeWriter_Create(estimate); + if (writer == NULL) { + return NULL; } - PyObject *name = PyObject_Repr(self->var_name); - if (name == NULL) { + if (PyUnicodeWriter_WriteUTF8(writer, "<ContextVar name=", 17) < 0) { goto error; } - if (_PyUnicodeWriter_WriteStr(&writer, name) < 0) { - Py_DECREF(name); + if (PyUnicodeWriter_WriteRepr(writer, self->var_name) < 0) { goto error; } - Py_DECREF(name); if (self->var_default != NULL) { - if (_PyUnicodeWriter_WriteASCIIString(&writer, " default=", 9) < 0) { - goto error; - } - - PyObject *def = PyObject_Repr(self->var_default); - if (def == NULL) { + if (PyUnicodeWriter_WriteUTF8(writer, " default=", 9) < 0) { goto error; } - if (_PyUnicodeWriter_WriteStr(&writer, def) < 0) { - Py_DECREF(def); + if (PyUnicodeWriter_WriteRepr(writer, self->var_default) < 0) { goto error; } - Py_DECREF(def); } - PyObject *addr = PyUnicode_FromFormat(" at %p>", self); - if (addr == NULL) { - goto error; - } - if (_PyUnicodeWriter_WriteStr(&writer, addr) < 0) { - Py_DECREF(addr); + if (PyUnicodeWriter_Format(writer, " at %p>", self) < 0) { goto error; } - Py_DECREF(addr); - - return _PyUnicodeWriter_Finish(&writer); + return PyUnicodeWriter_Finish(writer); error: - _PyUnicodeWriter_Dealloc(&writer); + PyUnicodeWriter_Discard(writer); return NULL; } |