]> granicus.if.org Git - python/commitdiff
Issue #13573: The csv.writer now uses the repr() for floats rather than str().
authorRaymond Hettinger <python@rcn.com>
Mon, 12 Dec 2011 06:31:09 +0000 (22:31 -0800)
committerRaymond Hettinger <python@rcn.com>
Mon, 12 Dec 2011 06:31:09 +0000 (22:31 -0800)
Lib/test/test_csv.py
Misc/NEWS
Modules/_csv.c

index 7b16e2db646cef29d3e5e28a0bbb7214633e9a14..681cfd8e853ae7169cb3306c0306be177826f211 100644 (file)
@@ -207,6 +207,18 @@ class Test_Csv(unittest.TestCase):
             fileobj.close()
             os.unlink(name)
 
+    def test_write_float(self):
+        # Issue 13573: loss of precision because csv.writer
+        # uses str() for floats instead of repr()
+        orig_row = [1.234567890123, 1.0/7.0, 'abc']
+        f = StringIO()
+        c = csv.writer(f, quoting=csv.QUOTE_NONNUMERIC)
+        c.writerow(orig_row)
+        f.seek(0)
+        c = csv.reader(f, quoting=csv.QUOTE_NONNUMERIC)
+        new_row = next(c)
+        self.assertEqual(orig_row, new_row)
+
     def _read_test(self, input, expect, **kwargs):
         reader = csv.reader(input, **kwargs)
         result = list(reader)
@@ -784,7 +796,7 @@ class TestArrayWrites(unittest.TestCase):
         try:
             writer = csv.writer(fileobj, dialect="excel")
             writer.writerow(a)
-            expected = ",".join([str(i) for i in a])+"\r\n"
+            expected = ",".join([repr(i) for i in a])+"\r\n"
             fileobj.seek(0)
             self.assertEqual(fileobj.read(), expected)
         finally:
@@ -800,7 +812,7 @@ class TestArrayWrites(unittest.TestCase):
         try:
             writer = csv.writer(fileobj, dialect="excel")
             writer.writerow(a)
-            expected = ",".join([str(i) for i in a])+"\r\n"
+            expected = ",".join([repr(i) for i in a])+"\r\n"
             fileobj.seek(0)
             self.assertEqual(fileobj.read(), expected)
         finally:
index 6a089e373b3ce208b252ae79d9b040a4920d8803..18196536f94142dc13c7608024c60de2cef04242 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -85,6 +85,9 @@ Library
 - tarfile.py: Correctly detect bzip2 compressed streams with blocksizes
   other than 900k.
 
+- Issue #13573: The csv.writer now uses the repr() for floats rather than str().
+  This allows floats to round-trip without loss of precision.
+
 - Issue #13439: Fix many errors in turtle docstrings.
 
 - Issue #12856: Ensure child processes do not inherit the parent's random
index 983f6a5043b651c65eb5a594447096721e81fb4a..ea3add2dbc4ac50eff2dcaa8c27c7063bb5aa167 100644 (file)
@@ -1184,7 +1184,11 @@ csv_writerow(WriterObj *self, PyObject *seq)
         else {
             PyObject *str;
 
-            str = PyObject_Str(field);
+            if (PyFloat_Check(field)) {
+                str = PyObject_Repr(field);
+            } else {
+                str = PyObject_Str(field);
+            }
             Py_DECREF(field);
             if (str == NULL)
                 return NULL;