comparison 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
comparison
equal deleted inserted replaced
41772:13641adba6ec 41782:bee8d01ef42c
1565 1565
1566 static PyObject * 1566 static PyObject *
1567 array_repr(arrayobject *a) 1567 array_repr(arrayobject *a)
1568 { 1568 {
1569 char buf[256], typecode; 1569 char buf[256], typecode;
1570 PyObject *s, *t, *v = NULL; 1570 PyObject *s, *v = NULL;
1571 Py_ssize_t len; 1571 Py_ssize_t len;
1572 1572
1573 len = a->ob_size; 1573 len = a->ob_size;
1574 typecode = a->ob_descr->typecode; 1574 typecode = a->ob_descr->typecode;
1575 if (len == 0) { 1575 if (len == 0) {
1576 PyOS_snprintf(buf, sizeof(buf), "array('%c')", typecode); 1576 return PyUnicode_FromFormat("array('%c')", typecode);
1577 return PyUnicode_FromString(buf); 1577 }
1578 }
1579
1580 if (typecode == 'c') 1578 if (typecode == 'c')
1581 v = array_tostring(a, NULL); 1579 v = array_tostring(a, NULL);
1582 else if (typecode == 'u') 1580 else if (typecode == 'u')
1583 v = array_tounicode(a, NULL); 1581 v = array_tounicode(a, NULL);
1584 else 1582 else
1585 v = array_tolist(a, NULL); 1583 v = array_tolist(a, NULL);
1586 t = PyObject_Repr(v); 1584
1587 Py_XDECREF(v); 1585 s = PyUnicode_FromFormat("array('%c', %R)", typecode, v);
1588 1586 Py_DECREF(v);
1589 PyOS_snprintf(buf, sizeof(buf), "array('%c', ", typecode);
1590 s = PyUnicode_FromString(buf);
1591 PyUnicode_AppendAndDel(&s, t);
1592 PyUnicode_AppendAndDel(&s, PyUnicode_FromString(")"));
1593 return s; 1587 return s;
1594 } 1588 }
1595 1589
1596 static PyObject* 1590 static PyObject*
1597 array_subscr(arrayobject* self, PyObject* item) 1591 array_subscr(arrayobject* self, PyObject* item)