@@ -853,7 +853,6 @@ _PyBuffer_ReleaseInInterpreterAndRawFree(PyInterpreterState *interp,
853853PyObject *
854854PyObject_Format (PyObject * obj , PyObject * format_spec )
855855{
856- PyObject * meth ;
857856 PyObject * empty = NULL ;
858857 PyObject * result = NULL ;
859858
@@ -880,21 +879,32 @@ PyObject_Format(PyObject *obj, PyObject *format_spec)
880879 format_spec = empty ;
881880 }
882881
883- /* Find the (unbound!) __format__ method */
884- meth = _PyObject_LookupSpecial (obj , & _Py_ID (__format__ ));
885- if (meth == NULL ) {
886- PyThreadState * tstate = _PyThreadState_GET ();
887- if (!_PyErr_Occurred (tstate )) {
888- _PyErr_Format (tstate , PyExc_TypeError ,
889- "Type %.100s doesn't define __format__" ,
890- Py_TYPE (obj )-> tp_name );
882+ /* Find the __format__ method and call it, without creating
883+ a temporary bound method where possible. */
884+ PyThreadState * tstate = _PyThreadState_GET ();
885+ _PyCStackRef cref ;
886+ _PyThreadState_PushCStackRef (tstate , & cref );
887+ _PyStackRef self = PyStackRef_FromPyObjectBorrow (obj );
888+ int found = _PyObject_LookupSpecialMethod (& _Py_ID (__format__ ),
889+ & cref .ref , & self );
890+ if (found > 0 ) {
891+ PyObject * meth = PyStackRef_AsPyObjectBorrow (cref .ref );
892+ PyObject * args [2 ] = {PyStackRef_AsPyObjectBorrow (self ), format_spec };
893+ if (args [0 ] != NULL ) {
894+ /* Unbound method: prepend self. */
895+ result = PyObject_Vectorcall (meth , args , 2 , NULL );
896+ }
897+ else {
898+ result = PyObject_Vectorcall (meth , args + 1 , 1 , NULL );
891899 }
892- goto done ;
893900 }
894-
895- /* And call it. */
896- result = PyObject_CallOneArg (meth , format_spec );
897- Py_DECREF (meth );
901+ else if (found == 0 ) {
902+ _PyErr_Format (tstate , PyExc_TypeError ,
903+ "Type %.100s doesn't define __format__" ,
904+ Py_TYPE (obj )-> tp_name );
905+ }
906+ PyStackRef_XCLOSE (self );
907+ _PyThreadState_PopCStackRef (tstate , & cref );
898908
899909 if (result && !PyUnicode_Check (result )) {
900910 PyErr_Format (PyExc_TypeError ,
0 commit comments