]> granicus.if.org Git - python/commitdiff
Issue #21350: Fix file.writelines() to accept arbitrary buffer objects, as advertised.
authorAntoine Pitrou <solipsis@pitrou.net>
Thu, 8 May 2014 17:26:04 +0000 (19:26 +0200)
committerAntoine Pitrou <solipsis@pitrou.net>
Thu, 8 May 2014 17:26:04 +0000 (19:26 +0200)
Patch by Brian Kearns.

Lib/test/test_file2k.py
Misc/NEWS
Objects/fileobject.c

index 7e74e64df644b5ce676e0f1de2347b01ca16f3c3..fae1db6acc2eda5dd63ca82d075ede261d30c1de 100644 (file)
@@ -89,6 +89,13 @@ class AutoFileTests(unittest.TestCase):
         self.assertRaises(TypeError, self.f.writelines,
                           [NonString(), NonString()])
 
+    def testWritelinesBuffer(self):
+        self.f.writelines([array('c', 'abc')])
+        self.f.close()
+        self.f = open(TESTFN, 'rb')
+        buf = self.f.read()
+        self.assertEqual(buf, 'abc')
+
     def testRepr(self):
         # verify repr works
         self.assertTrue(repr(self.f).startswith("<open file '" + TESTFN))
index 9e50bc895fad6a64bbd614f37760bf0358be3a39..a026b263ef51d3c2164931e208381532055d33ab 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -10,6 +10,9 @@ What's New in Python 2.7.7?
 Core and Builtins
 -----------------
 
+- Issue #21350: Fix file.writelines() to accept arbitrary buffer objects,
+  as advertised.  Patch by Brian Kearns.
+
 - Issue #20437: Fixed 43 potential bugs when deleting objects references.
 
 - Issue #21134: Fix segfault when str is called on an uninitialized
index c5e09612e261b1c906495a3150b4c9bc7b188b1e..559405869dcaed3e5467cd5dcc13d6d61a0130b7 100644 (file)
@@ -1941,13 +1941,13 @@ file_writelines(PyFileObject *f, PyObject *seq)
             PyObject *v = PyList_GET_ITEM(list, i);
             if (!PyString_Check(v)) {
                 const char *buffer;
-                if (((f->f_binary &&
-                      PyObject_AsReadBuffer(v,
-                          (const void**)&buffer,
-                                        &len)) ||
-                     PyObject_AsCharBuffer(v,
-                                           &buffer,
-                                           &len))) {
+                int res;
+                if (f->f_binary) {
+                    res = PyObject_AsReadBuffer(v, (const void**)&buffer, &len);
+                } else {
+                    res = PyObject_AsCharBuffer(v, &buffer, &len);
+                }
+                if (res) {
                     PyErr_SetString(PyExc_TypeError,
             "writelines() argument must be a sequence of strings");
                             goto error;