Skip to content

gh-119182: Use public PyUnicodeWriter in contextvar_tp_repr() #120809

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 20, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 15 additions & 32 deletions Python/context.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
Loading