[Python-3000] close() on open(fd, closefd=False)

Christian Heimes lists at cheimes.de
Mon Nov 3 00:35:20 CET 2008


Martin v. Löwis wrote:
> However, this is the documented behavior:
> 
> "the underlying file descriptor will be kept open when the file is closed."
> 
> and, for close
> 
> "Flush and close this stream."
> 
> It would help if the documentation of close would read
> 
> "Flush and close this stream. This method has no effect if the file is
> already closed, or if closefd was False when the file object was created."

I would use a slightly different wording

"Flush and close this stream. This method has no effect if the file is
already closed. Once the file is closed, any operation on the file (e.g. 
reading or writing) will fail. Close doesn't close the internal file 
descriptor  if closefd was False when the file object was created."

In my opinion close() should render the file *object* disabled in all 
cases. closefd should just leave the file *descriptor* open, not the 
file *object*.

> It might be useful if closefd attribute could be reflected, so that
> applications that know about it and really want to close the file
> still can do that.

Agreed! My latest patch adds a read only attribute closefd.

> Also, is it really the case that close has no effect if closefd
> was given? ISTM that it will still flush the file, for a
> _BufferedIOMixin. This should systematically be clarified: it
> should either always flush, or never (although "always flush"
> seems more useful).

I haven't looked at the code in the io yet. Our discussion was mostly 
about the _fileio C extension. To clarify the issue with an example

 >>> out = open(1, "w", closefd=False)
 >>> out.write("example\n")
example
8
 >>> out.close()
/usr/local/lib/python3.0/io.py:1461: RuntimeWarning: Trying to close 
unclosable fd!
   self.buffer.close()
 >>> out.write("example\n")
example
8

I think the second out.write() call should raise an exception instead of 
writing the string to the fd 1.

> Also, why does the _BufferedIOMixin discard exceptions from flush?
> Errors should never pass silently.

Ack!

> Also, why does the FileIO.close first invoke _FileIO.close, then
> RawIOBase.close? IIUC, FileIO.close will close the file handle,
> yet RawIOBase will attempt to flush afterwards.

Apparently the io module hasn't been reviewed for its massive usage of 
close. :/

Christian


More information about the Python-3000 mailing list