Fix str() and repr() of empty sets.

This commit is contained in:
Georg Brandl 2006-08-28 19:37:11 +00:00
parent b3fa66fe30
commit c4996ba794
2 changed files with 16 additions and 5 deletions

View File

@ -631,7 +631,7 @@ class TestBasicOpsEmpty(TestBasicOps):
self.set = set(self.values) self.set = set(self.values)
self.dup = set(self.values) self.dup = set(self.values)
self.length = 0 self.length = 0
self.repr = "{}" self.repr = "set()"
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------

View File

@ -529,10 +529,17 @@ set_tp_print(PySetObject *so, FILE *fp, int flags)
Py_ssize_t pos=0; Py_ssize_t pos=0;
char *emit = ""; /* No separator emitted on first pass */ char *emit = ""; /* No separator emitted on first pass */
char *separator = ", "; char *separator = ", ";
int literalform = 0;
if (so->ob_type == &PySet_Type) if (!so->used) {
fprintf(fp, "%s()", so->ob_type->tp_name);
return 0;
}
if (so->ob_type == &PySet_Type) {
literalform = 1;
fprintf(fp, "{"); fprintf(fp, "{");
else } else
fprintf(fp, "%s([", so->ob_type->tp_name); fprintf(fp, "%s([", so->ob_type->tp_name);
while (set_next(so, &pos, &entry)) { while (set_next(so, &pos, &entry)) {
fputs(emit, fp); fputs(emit, fp);
@ -540,7 +547,7 @@ set_tp_print(PySetObject *so, FILE *fp, int flags)
if (PyObject_Print(entry->key, fp, 0) != 0) if (PyObject_Print(entry->key, fp, 0) != 0)
return -1; return -1;
} }
if (so->ob_type == &PySet_Type) if (literalform)
fputs("}", fp); fputs("}", fp);
else else
fputs("])", fp); fputs("])", fp);
@ -552,6 +559,10 @@ set_repr(PySetObject *so)
{ {
PyObject *keys, *result, *listrepr; PyObject *keys, *result, *listrepr;
/* shortcut for the empty set */
if (!so->used)
return PyString_FromFormat("%s()", so->ob_type->tp_name);
keys = PySequence_List((PyObject *)so); keys = PySequence_List((PyObject *)so);
if (keys == NULL) if (keys == NULL)
return NULL; return NULL;
@ -567,7 +578,7 @@ set_repr(PySetObject *so)
result = PyString_FromFormat("{%s}", s); result = PyString_FromFormat("{%s}", s);
} else { } else {
result = PyString_FromFormat("%s(%s)", so->ob_type->tp_name, result = PyString_FromFormat("%s(%s)", so->ob_type->tp_name,
PyString_AS_STRING(listrepr)); PyString_AS_STRING(listrepr));
} }
Py_DECREF(listrepr); Py_DECREF(listrepr);
return result; return result;