]> granicus.if.org Git - python/commitdiff
Fix str() and repr() of empty sets.
authorGeorg Brandl <georg@python.org>
Mon, 28 Aug 2006 19:37:11 +0000 (19:37 +0000)
committerGeorg Brandl <georg@python.org>
Mon, 28 Aug 2006 19:37:11 +0000 (19:37 +0000)
Lib/test/test_set.py
Objects/setobject.c

index 556e390259aa3cc0757d67e63eb1c6ccc96a266f..03621a67fd2b8e35736528ee707a444a5178f59c 100644 (file)
@@ -631,7 +631,7 @@ class TestBasicOpsEmpty(TestBasicOps):
         self.set    = set(self.values)
         self.dup    = set(self.values)
         self.length = 0
-        self.repr   = "{}"
+        self.repr   = "set()"
 
 #------------------------------------------------------------------------------
 
index b4b58b7afaab0885d31a0b676fc986c17de2c5e9..05549e6cfffc05646b2261d1a3450d8de1087c4b 100644 (file)
@@ -529,10 +529,17 @@ set_tp_print(PySetObject *so, FILE *fp, int flags)
        Py_ssize_t pos=0;
        char *emit = "";        /* No separator emitted on first pass */
        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, "{");
-       else
+       else
                fprintf(fp, "%s([", so->ob_type->tp_name);
        while (set_next(so, &pos, &entry)) {
                fputs(emit, fp);
@@ -540,7 +547,7 @@ set_tp_print(PySetObject *so, FILE *fp, int flags)
                if (PyObject_Print(entry->key, fp, 0) != 0)
                        return -1;
        }
-       if (so->ob_type == &PySet_Type)
+       if (literalform)
                fputs("}", fp);
        else
                fputs("])", fp);
@@ -552,6 +559,10 @@ set_repr(PySetObject *so)
 {
        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);
        if (keys == NULL)
                return NULL;
@@ -567,7 +578,7 @@ set_repr(PySetObject *so)
                result = PyString_FromFormat("{%s}", s);
        } else {
                result = PyString_FromFormat("%s(%s)", so->ob_type->tp_name,
-                        PyString_AS_STRING(listrepr));
+                               PyString_AS_STRING(listrepr));
        }
        Py_DECREF(listrepr);
        return result;