diff --git a/Lib/test/test_io.py b/Lib/test/test_io.py index 96258b4ccd7..f5bb732ad9c 100644 --- a/Lib/test/test_io.py +++ b/Lib/test/test_io.py @@ -643,6 +643,19 @@ class IOTest(unittest.TestCase): with self.open("non-existent", "r", opener=opener) as f: self.assertEqual(f.read(), "egg\n") + 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): diff --git a/Modules/_io/fileio.c b/Modules/_io/fileio.c index df3affe1ee2..726d17b67e2 100644 --- a/Modules/_io/fileio.c +++ b/Modules/_io/fileio.c @@ -230,9 +230,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|siO:fileio",