Mercurial > cpython-lru_cache-weakref
diff Objects/setobject.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 | e70cdce0e8b2 |
line wrap: on
line diff
--- a/Objects/setobject.c Fri May 18 22:12:08 2007 +0000 +++ b/Objects/setobject.c Sat May 19 21:49:49 2007 +0000 @@ -612,10 +612,8 @@ static PyObject * set_repr(PySetObject *so) { - PyObject *keys, *result=NULL, *listrepr; - int newsize; + PyObject *keys, *result=NULL; Py_UNICODE *u; - const char *s; int status = Py_ReprEnter((PyObject*)so); if (status != 0) { @@ -633,35 +631,32 @@ keys = PySequence_List((PyObject *)so); if (keys == NULL) goto done; - listrepr = PyObject_Repr(keys); - Py_DECREF(keys); - if (listrepr == NULL) - goto done; - newsize = PyUnicode_GET_SIZE(listrepr); - if (so->ob_type != &PySet_Type) - newsize += strlen(so->ob_type->tp_name)+2; - result = PyUnicode_FromUnicode(NULL, newsize); - if (result) { - u = PyUnicode_AS_UNICODE(result); - if (so->ob_type != &PySet_Type) { - for (s = so->ob_type->tp_name; *s;) - *u++ = *s++; - *u++ = '('; - Py_UNICODE_COPY(u, PyUnicode_AS_UNICODE(listrepr), - PyUnicode_GET_SIZE(listrepr)); - u += PyUnicode_GET_SIZE(listrepr); - *u++ = ')'; - } else { + if (so->ob_type != &PySet_Type) { + result = PyUnicode_FromFormat("%s(%R)", so->ob_type->tp_name, keys); + Py_DECREF(keys); + } + else { + PyObject *listrepr = PyObject_Repr(keys); + Py_ssize_t newsize; + Py_DECREF(keys); + if (listrepr == NULL) { + Py_DECREF(keys); + goto done; + } + newsize = PyUnicode_GET_SIZE(listrepr); + result = PyUnicode_FromUnicode(NULL, newsize); + if (result) { + u = PyUnicode_AS_UNICODE(result); *u++ = '{'; /* Omit the brackets from the listrepr */ Py_UNICODE_COPY(u, PyUnicode_AS_UNICODE(listrepr)+1, - PyUnicode_GET_SIZE(listrepr)-2); - u += PyUnicode_GET_SIZE(listrepr)-2; + PyUnicode_GET_SIZE(listrepr)-2); + u += newsize-2; *u++ = '}'; } + Py_DECREF(listrepr); } - Py_DECREF(listrepr); done: Py_ReprLeave((PyObject*)so); return result;
