Skip to content

Commit 5b7be71

Browse files
committed
pythongh-125196: Use PyUnicodeWriter for repr(contextvars.Token)
Replace the private _PyUnicodeWriter with the public PyUnicodeWriter.
1 parent 9bda775 commit 5b7be71

File tree

2 files changed

+19
-28
lines changed

2 files changed

+19
-28
lines changed

Lib/test/test_context.py

+8
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,14 @@ def test_context_var_repr_1(self):
6060
c.reset(t)
6161
self.assertIn(' used ', repr(t))
6262

63+
@isolated_context
64+
def test_token_repr_1(self):
65+
c = contextvars.ContextVar('a')
66+
tok = c.set(1)
67+
self.assertRegex(repr(tok),
68+
r"^<Token var=<ContextVar name='a' "
69+
r"at 0x[0-9a-f]+> at 0x[0-9a-f]+>$")
70+
6371
def test_context_subclassing_1(self):
6472
with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):
6573
class MyContextVar(contextvars.ContextVar):

Python/context.c

+11-28
Original file line numberDiff line numberDiff line change
@@ -1154,48 +1154,31 @@ token_tp_dealloc(PyContextToken *self)
11541154
static PyObject *
11551155
token_tp_repr(PyContextToken *self)
11561156
{
1157-
_PyUnicodeWriter writer;
1158-
1159-
_PyUnicodeWriter_Init(&writer);
1160-
1161-
if (_PyUnicodeWriter_WriteASCIIString(&writer, "<Token", 6) < 0) {
1157+
PyUnicodeWriter *writer = PyUnicodeWriter_Create(0);
1158+
if (writer == NULL) {
1159+
return NULL;
1160+
}
1161+
if (PyUnicodeWriter_WriteUTF8(writer, "<Token", 6) < 0) {
11621162
goto error;
11631163
}
1164-
11651164
if (self->tok_used) {
1166-
if (_PyUnicodeWriter_WriteASCIIString(&writer, " used", 5) < 0) {
1165+
if (PyUnicodeWriter_WriteUTF8(writer, " used", 5) < 0) {
11671166
goto error;
11681167
}
11691168
}
1170-
1171-
if (_PyUnicodeWriter_WriteASCIIString(&writer, " var=", 5) < 0) {
1169+
if (PyUnicodeWriter_WriteUTF8(writer, " var=", 5) < 0) {
11721170
goto error;
11731171
}
1174-
1175-
PyObject *var = PyObject_Repr((PyObject *)self->tok_var);
1176-
if (var == NULL) {
1172+
if (PyUnicodeWriter_WriteRepr(writer, (PyObject *)self->tok_var) < 0) {
11771173
goto error;
11781174
}
1179-
if (_PyUnicodeWriter_WriteStr(&writer, var) < 0) {
1180-
Py_DECREF(var);
1181-
goto error;
1182-
}
1183-
Py_DECREF(var);
1184-
1185-
PyObject *addr = PyUnicode_FromFormat(" at %p>", self);
1186-
if (addr == NULL) {
1187-
goto error;
1188-
}
1189-
if (_PyUnicodeWriter_WriteStr(&writer, addr) < 0) {
1190-
Py_DECREF(addr);
1175+
if (PyUnicodeWriter_Format(writer, " at %p>", self) < 0) {
11911176
goto error;
11921177
}
1193-
Py_DECREF(addr);
1194-
1195-
return _PyUnicodeWriter_Finish(&writer);
1178+
return PyUnicodeWriter_Finish(writer);
11961179

11971180
error:
1198-
_PyUnicodeWriter_Dealloc(&writer);
1181+
PyUnicodeWriter_Discard(writer);
11991182
return NULL;
12001183
}
12011184

0 commit comments

Comments
 (0)