roganjosh roganjosh - 1 month ago 5
Python Question

Why can you close() a file object more than once?

This question is purely out of curiosity. Brought up in a recent discussion for a question here, I've often wondered why the context manager (

) does not throw an error when people explicitly close the file anyway through misunderstanding... and then I found that you can call
on a file multiple times with no error even without using

The only thing we can find relating to this is here and it just blandly says (emphasis mine):

close( )

Close the file. A closed file cannot be read or written any more. Any operation which requires that the file be open will raise a ValueError after the file has been closed. Calling close() more than once is allowed.

It would appear that this is intentional by design but, if you can't perform any operations on the closed file without an exception, we can't work out why closing the file multiple times is permitted. Is there a use case?

  1. Thinking about with is just wrong. This behaviour has been in Python forever and thus it's worth keeping it for backward compatibility.

  2. Because it would serve no purpose to raise an exception. If you have an actual bug in your code where you might close the file before finishing using it, you'll get an exception when using the read or write operations anyway, and thus you'll never reach the second call to close.

  3. Allowing this will rarely make the code easier to write avoiding adding lots of if not the_file.isclosed(): the_file.close().

  4. The BDFL designed the file objects in that way and we are stuck with that behaviour since there's no strong reason to change it.