diff Modules/arraymodule.c @ 41782:bee8d01ef42c

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).
author Walter Dörwald <walter@livinglogic.de>
date Sat, 19 May 2007 21:49:49 +0000
parents b29d71d43c80
children 00413f70ce5c
line wrap: on
line diff
--- a/Modules/arraymodule.c	Fri May 18 22:12:08 2007 +0000
+++ b/Modules/arraymodule.c	Sat May 19 21:49:49 2007 +0000
@@ -1567,29 +1567,23 @@
 array_repr(arrayobject *a)
 {
 	char buf[256], typecode;
-	PyObject *s, *t, *v = NULL;
+	PyObject *s, *v = NULL;
 	Py_ssize_t len;
 
 	len = a->ob_size;
 	typecode = a->ob_descr->typecode;
 	if (len == 0) {
-		PyOS_snprintf(buf, sizeof(buf), "array('%c')", typecode);
-		return PyUnicode_FromString(buf);
+		return PyUnicode_FromFormat("array('%c')", typecode);
 	}
-		
 	if (typecode == 'c')
 		v = array_tostring(a, NULL);
 	else if (typecode == 'u')
 		v = array_tounicode(a, NULL);
 	else
 		v = array_tolist(a, NULL);
-	t = PyObject_Repr(v);
-	Py_XDECREF(v);
 
-	PyOS_snprintf(buf, sizeof(buf), "array('%c', ", typecode);
-	s = PyUnicode_FromString(buf);
-	PyUnicode_AppendAndDel(&s, t);
-	PyUnicode_AppendAndDel(&s, PyUnicode_FromString(")"));
+	s = PyUnicode_FromFormat("array('%c', %R)", typecode, v);
+	Py_DECREF(v);
 	return s;
 }