Skip to content

Commit a677bc8

Browse files
gh-162227: Fix scaling of format() with a format spec on the free-threaded build
PyObject_Format() now looks up __format__ with _PyObject_LookupSpecialMethod(), avoiding a temporary bound method and reference count contention on the shared method object.
1 parent e8fb673 commit a677bc8

2 files changed

Lines changed: 28 additions & 14 deletions

File tree

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Improve multi-threaded scaling of :func:`format`, f-strings and
2+
:meth:`str.format` with a format specification on the :term:`free-threaded
3+
build` by avoiding the creation of a temporary bound method and reference
4+
count contention on the shared ``__format__`` method.

‎Objects/abstract.c‎

Lines changed: 24 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -853,7 +853,6 @@ _PyBuffer_ReleaseInInterpreterAndRawFree(PyInterpreterState *interp,
853853
PyObject *
854854
PyObject_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

Comments
 (0)