Why can you close() a file object more than once?
<p>This question is purely out of curiosity. Brought up in a recent discussion for a question <a href="http://stackoverflow.com/questions/39599926/what-does-with-open-do-in-this-situation/39600026?noredirect=1#39600026">here</a>, I've often wondered why the context manager (<code>with</code>) does not throw an error when people explicitly close the file anyway through misunderstanding... and then I found that you can call <code>close()</code> on a file multiple times with no error even without using <code>with</code>.</p>

<p>The only thing we can find relating to this is <a href="https://docs.python.org/2.4/lib/bltin-file-objects.html" rel="nofollow">here</a> and it just blandly says (emphasis mine):</p>

<blockquote>
  <p>close(    ) <br>
  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. <strong>Calling close() more than once is allowed</strong>.</p>
</blockquote>

<p>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?</p>

<ol>
<li><p>Thinking about <code>with</code> is just wrong. This behaviour has been in Python <em>forever</em> and thus it's worth keeping it for backward compatibility.</p></li>
<li><p>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 <code>read</code> or <code>write</code> operations anyway, and thus you'll never reach the second call to <code>close</code>.</p></li>
<li><p>Allowing this will <em>rarely</em> make the code easier to write avoiding adding lots of <code>if not the_file.isclosed(): the_file.close()</code>.</p></li>
<li><p>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.</p></li>
</ol>

python