Add a format specifier %R to PyUnicode_FromFormat(), which embeds
the result of a call to PyObject_Repr() into the string. This makes
it possible to simplify many repr implementations.
PyUnicode_FromFormat() uses two steps to create the final string: A first
pass through the format string determines the size of the final string and
a second pass creates the string. To avoid calling PyObject_Repr() twice
for each %R specifier, PyObject_Repr() is called during the size
calculation step and the results are stored in an array (whose size is
determined at the start by counting %R specifiers).
diff --git a/Modules/_collectionsmodule.c b/Modules/_collectionsmodule.c
index 1311d4d..fc4ef15 100644
--- a/Modules/_collectionsmodule.c
+++ b/Modules/_collectionsmodule.c
@@ -627,14 +627,7 @@
return NULL;
}
- result = PyUnicode_FromString("deque(");
- if (result == NULL) {
- Py_DECREF(aslist);
- Py_ReprLeave(deque);
- return NULL;
- }
- PyUnicode_AppendAndDel(&result, PyObject_Repr(aslist));
- PyUnicode_AppendAndDel(&result, PyUnicode_FromString(")"));
+ result = PyUnicode_FromFormat("deque(%R)", aslist);
Py_DECREF(aslist);
Py_ReprLeave(deque);
return result;
@@ -1208,25 +1201,18 @@
static PyObject *
defdict_repr(defdictobject *dd)
{
- PyObject *defrepr;
PyObject *baserepr;
+ PyObject *def;
PyObject *result;
baserepr = PyDict_Type.tp_repr((PyObject *)dd);
if (baserepr == NULL)
return NULL;
if (dd->default_factory == NULL)
- defrepr = PyUnicode_FromString("None");
+ def = Py_None;
else
- defrepr = PyObject_Repr(dd->default_factory);
- if (defrepr == NULL) {
- Py_DECREF(baserepr);
- return NULL;
- }
- result = PyUnicode_FromString("defaultdict(");
- PyUnicode_AppendAndDel(&result, defrepr);
- PyUnicode_AppendAndDel(&result, PyUnicode_FromString(", "));
- PyUnicode_AppendAndDel(&result, baserepr);
- PyUnicode_AppendAndDel(&result, PyUnicode_FromString(")"));
+ def = dd->default_factory;
+ result = PyUnicode_FromFormat("defaultdict(%R, %U)", def, baserepr);
+ Py_DECREF(baserepr);
return result;
}