@@ -893,56 +893,39 @@ contextvar_tp_hash(PyContextVar *self)
893
893
static PyObject *
894
894
contextvar_tp_repr (PyContextVar * self )
895
895
{
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 ;
904
904
}
905
905
906
- PyObject * name = PyObject_Repr (self -> var_name );
907
- if (name == NULL ) {
906
+ if (PyUnicodeWriter_WriteUTF8 (writer , "<ContextVar name=" , 17 ) < 0 ) {
908
907
goto error ;
909
908
}
910
- if (_PyUnicodeWriter_WriteStr (& writer , name ) < 0 ) {
911
- Py_DECREF (name );
909
+ if (PyUnicodeWriter_WriteRepr (writer , self -> var_name ) < 0 ) {
912
910
goto error ;
913
911
}
914
- Py_DECREF (name );
915
912
916
913
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 ) {
923
915
goto error ;
924
916
}
925
- if (_PyUnicodeWriter_WriteStr (& writer , def ) < 0 ) {
926
- Py_DECREF (def );
917
+ if (PyUnicodeWriter_WriteRepr (writer , self -> var_default ) < 0 ) {
927
918
goto error ;
928
919
}
929
- Py_DECREF (def );
930
920
}
931
921
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 ) {
938
923
goto error ;
939
924
}
940
- Py_DECREF (addr );
941
-
942
- return _PyUnicodeWriter_Finish (& writer );
925
+ return PyUnicodeWriter_Finish (writer );
943
926
944
927
error :
945
- _PyUnicodeWriter_Dealloc ( & writer );
928
+ PyUnicodeWriter_Discard ( writer );
946
929
return NULL ;
947
930
}
948
931
0 commit comments