[Python-checkins] cpython (2.7): Issue #13573: The csv.writer now uses the repr() for floats rather than str().
raymond.hettinger
python-checkins at python.org
Mon Dec 12 07:31:21 CET 2011
http://hg.python.org/cpython/rev/bf7329190ca6
changeset: 73944:bf7329190ca6
branch: 2.7
parent: 73922:fd5f43737546
user: Raymond Hettinger <python at rcn.com>
date: Sun Dec 11 22:31:09 2011 -0800
summary:
Issue #13573: The csv.writer now uses the repr() for floats rather than str().
files:
Lib/test/test_csv.py | 16 ++++++++++++++--
Misc/NEWS | 3 +++
Modules/_csv.c | 6 +++++-
3 files changed, 22 insertions(+), 3 deletions(-)
diff --git a/Lib/test/test_csv.py b/Lib/test/test_csv.py
--- a/Lib/test/test_csv.py
+++ b/Lib/test/test_csv.py
@@ -207,6 +207,18 @@
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 @@
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 @@
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:
diff --git a/Misc/NEWS b/Misc/NEWS
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -85,6 +85,9 @@
- 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
diff --git a/Modules/_csv.c b/Modules/_csv.c
--- a/Modules/_csv.c
+++ b/Modules/_csv.c
@@ -1184,7 +1184,11 @@
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;
--
Repository URL: http://hg.python.org/cpython
More information about the Python-checkins
mailing list