]> granicus.if.org Git - python/commitdiff
#4841: Fix FileIO constructor to honor closefd when called repeatedly
authorHynek Schlawack <hs@ox.cx>
Fri, 25 May 2012 07:24:18 +0000 (09:24 +0200)
committerHynek Schlawack <hs@ox.cx>
Fri, 25 May 2012 07:24:18 +0000 (09:24 +0200)
Patch by Victor Stinner.

Lib/test/test_io.py
Modules/_io/fileio.c

index b9972f3ac56573d1047684da840b04de282c8e8f..72feff59e4e0c082a656150eafe10151e683c627 100644 (file)
@@ -593,6 +593,19 @@ class IOTest(unittest.TestCase):
         self.assertEqual(rawio.read(2), None)
         self.assertEqual(rawio.read(2), b"")
 
+    def test_fileio_closefd(self):
+        # Issue #4841
+        with self.open(__file__, 'rb') as f1, \
+             self.open(__file__, 'rb') as f2:
+            fileio = self.FileIO(f1.fileno(), closefd=False)
+            # .__init__() must not close f1
+            fileio.__init__(f2.fileno(), closefd=False)
+            f1.readline()
+            # .close() must not close f2
+            fileio.close()
+            f2.readline()
+
+
 class CIOTest(IOTest):
 
     def test_IOBase_finalize(self):
index 0048240b791085bedf3ee6f57e459ff65a8ed635..d1941dfa74edae90f4b77b1127fa8c6d2f940ec6 100644 (file)
@@ -198,9 +198,13 @@ fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
 
     assert(PyFileIO_Check(oself));
     if (self->fd >= 0) {
-        /* Have to close the existing file first. */
-        if (internal_close(self) < 0)
-            return -1;
+        if (self->closefd) {
+            /* Have to close the existing file first. */
+            if (internal_close(self) < 0)
+                return -1;
+        }
+        else
+            self->fd = -1;
     }
 
     if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio",