@@ -893,56 +893,39 @@ contextvar_tp_hash(PyContextVar *self)
893893static PyObject *
894894contextvar_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
944927error :
945- _PyUnicodeWriter_Dealloc ( & writer );
928+ PyUnicodeWriter_Discard ( writer );
946929 return NULL ;
947930}
948931
0 commit comments