Skip to content

Commit 56657f6

Browse files
authored
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.
1 parent 5150795 commit 56657f6

File tree

1 file changed

+15
-32
lines changed

1 file changed

+15
-32
lines changed

Python/context.c

Lines changed: 15 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -893,56 +893,39 @@ contextvar_tp_hash(PyContextVar *self)
893893
static PyObject *
894894
contextvar_tp_repr(PyContextVar *self)
895895
{
896-
_PyUnicodeWriter writer;
897-
898-
_PyUnicodeWriter_Init(&writer);
899-
900-
if (_PyUnicodeWriter_WriteASCIIString(
901-
&writer, "<ContextVar name=", 17) < 0)
902-
{
903-
goto error;
896+
// Estimation based on the shortest name and default value,
897+
// but maximize the pointer size.
898+
// "<ContextVar name='a' at 0x1234567812345678>"
899+
// "<ContextVar name='a' default=1 at 0x1234567812345678>"
900+
Py_ssize_t estimate = self->var_default ? 53 : 43;
901+
PyUnicodeWriter *writer = PyUnicodeWriter_Create(estimate);
902+
if (writer == NULL) {
903+
return NULL;
904904
}
905905

906-
PyObject *name = PyObject_Repr(self->var_name);
907-
if (name == NULL) {
906+
if (PyUnicodeWriter_WriteUTF8(writer, "<ContextVar name=", 17) < 0) {
908907
goto error;
909908
}
910-
if (_PyUnicodeWriter_WriteStr(&writer, name) < 0) {
911-
Py_DECREF(name);
909+
if (PyUnicodeWriter_WriteRepr(writer, self->var_name) < 0) {
912910
goto error;
913911
}
914-
Py_DECREF(name);
915912

916913
if (self->var_default != NULL) {
917-
if (_PyUnicodeWriter_WriteASCIIString(&writer, " default=", 9) < 0) {
918-
goto error;
919-
}
920-
921-
PyObject *def = PyObject_Repr(self->var_default);
922-
if (def == NULL) {
914+
if (PyUnicodeWriter_WriteUTF8(writer, " default=", 9) < 0) {
923915
goto error;
924916
}
925-
if (_PyUnicodeWriter_WriteStr(&writer, def) < 0) {
926-
Py_DECREF(def);
917+
if (PyUnicodeWriter_WriteRepr(writer, self->var_default) < 0) {
927918
goto error;
928919
}
929-
Py_DECREF(def);
930920
}
931921

932-
PyObject *addr = PyUnicode_FromFormat(" at %p>", self);
933-
if (addr == NULL) {
934-
goto error;
935-
}
936-
if (_PyUnicodeWriter_WriteStr(&writer, addr) < 0) {
937-
Py_DECREF(addr);
922+
if (PyUnicodeWriter_Format(writer, " at %p>", self) < 0) {
938923
goto error;
939924
}
940-
Py_DECREF(addr);
941-
942-
return _PyUnicodeWriter_Finish(&writer);
925+
return PyUnicodeWriter_Finish(writer);
943926

944927
error:
945-
_PyUnicodeWriter_Dealloc(&writer);
928+
PyUnicodeWriter_Discard(writer);
946929
return NULL;
947930
}
948931

0 commit comments

Comments
 (0)