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>

<p>Resource management is a big deal.  It's part of the reason why we have context managers in the first place.</p>

<p>I'm <em>guessing</em> that the core development team thought that it is better to make it "safe" to call close more than once to encourage people to close their files.  Otherwise, you could get yourself into a situation where you're asking "Was this closed before?".  If <code>.close()</code> couldn't be called multiple times, the only option would be to put your <code>file.close()</code> call in a <code>try</code>/<code>except</code> clause.  That makes the code uglier and (frankly), lots of people probably would just delete the call to <code>file.close()</code> rather than handle it properly.  In this case, it's just convenient to be able to call <code>file.close()</code> without worrying about any consequences since it's almost certain to succeed and leave you with a file that you know is closed afterward.</p>

python