Skip to content

Commit 2cc7156

Browse files
committed
#4841: Fix FileIO constructor to honor closefd when called repeatedly
Patch by Victor Stinner.
1 parent 1a01ebc commit 2cc7156

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
@@ -634,6 +634,19 @@ def test_types_have_dict(self):
634634
for obj in test:
635635
self.assertTrue(hasattr(obj, "__dict__"))
636636

637+
def test_fileio_closefd(self):
638+
# Issue #4841
639+
with self.open(__file__, 'rb') as f1, \
640+
self.open(__file__, 'rb') as f2:
641+
fileio = self.FileIO(f1.fileno(), closefd=False)
642+
# .__init__() must not close f1
643+
fileio.__init__(f2.fileno(), closefd=False)
644+
f1.readline()
645+
# .close() must not close f2
646+
fileio.close()
647+
f2.readline()
648+
649+
637650
class CIOTest(IOTest):
638651

639652
def test_IOBase_finalize(self):

Modules/_io/fileio.c

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

228228
assert(PyFileIO_Check(oself));
229229
if (self->fd >= 0) {
230-
/* Have to close the existing file first. */
231-
if (internal_close(self) < 0)
232-
return -1;
230+
if (self->closefd) {
231+
/* Have to close the existing file first. */
232+
if (internal_close(self) < 0)
233+
return -1;
234+
}
235+
else
236+
self->fd = -1;
233237
}
234238

235239
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio",

0 commit comments

Comments
 (0)