Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 9866d96

Browse files
committed
#4841: Fix FileIO constructor to honor closefd when called repeatedly
Patch by Victor Stinner.
2 parents 18eac4a + 2cc7156 commit 9866d96

2 files changed

Lines changed: 20 additions & 3 deletions

File tree

Lib/test/test_io.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -643,6 +643,19 @@ def opener(path, flags):
643643
with self.open("non-existent", "r", opener=opener) as f:
644644
self.assertEqual(f.read(), "egg\n")
645645

646+
def test_fileio_closefd(self):
647+
# Issue #4841
648+
with self.open(__file__, 'rb') as f1, \
649+
self.open(__file__, 'rb') as f2:
650+
fileio = self.FileIO(f1.fileno(), closefd=False)
651+
# .__init__() must not close f1
652+
fileio.__init__(f2.fileno(), closefd=False)
653+
f1.readline()
654+
# .close() must not close f2
655+
fileio.close()
656+
f2.readline()
657+
658+
646659
class CIOTest(IOTest):
647660

648661
def test_IOBase_finalize(self):

Modules/_io/fileio.c

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -230,9 +230,13 @@ fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
230230

231231
assert(PyFileIO_Check(oself));
232232
if (self->fd >= 0) {
233-
/* Have to close the existing file first. */
234-
if (internal_close(self) < 0)
235-
return -1;
233+
if (self->closefd) {
234+
/* Have to close the existing file first. */
235+
if (internal_close(self) < 0)
236+
return -1;
237+
}
238+
else
239+
self->fd = -1;
236240
}
237241

238242
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|siO:fileio",

0 commit comments

Comments
 (0)