This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Inconsistent behavior of IOBase methods on closed files
Type: behavior Stage:
Components: IO Versions: Python 3.3
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: BreamoreBoy, benjamin.peterson, dwight.guth, hynek, martin.panter, pitrou, stutzbach
Priority: normal Keywords:

Created on 2013-05-28 16:31 by dwight.guth, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Messages (4)
msg190224 - (view) Author: Dwight Guth (dwight.guth) Date: 2013-05-28 16:31
Consider the following program:

import io 
class A(io.IOBase): 
  def __init__(self): 
    self.x = 5 
  def read(self, limit=-1): 
    self.x -= 1 
    if self.x > 0: 
      return b"5" 
    return b"" 
  def seek(self, offset, whence=0): 
    return 0 
  def write(self, b): 
    pass 
 
a = A() 
a.close() 
assert a.__next__() == b"5555" 
assert a.readline() == b"" 
assert a.tell() == 0

These three operations succeed, even though the file is closed. However, these two operations fail:

a.readlines()
a.writelines([])

Why do some of the mixin methods on IOBase call _checkClosed and others don't?
msg220396 - (view) Author: Mark Lawrence (BreamoreBoy) * Date: 2014-06-12 23:07
Could we have a response for the record please.
msg237003 - (view) Author: Mark Lawrence (BreamoreBoy) * Date: 2015-03-02 01:41
Anybody?
msg248096 - (view) Author: Martin Panter (martin.panter) * (Python committer) Date: 2015-08-06 03:07
The documentation <https://docs.python.org/dev/library/io.html#io.IOBase> says “. . . calling any method (even inquiries) on a closed stream is undefined. Implementations may raise ValueError”. So IMO you shouldn’t rely on any particular success or failure behaviour of these methods when a stream is closed.

Having the stream methods waste time calling out to Python methods and descriptors like readable() and “closed” all the time can make things unnecessarily slow and inefficient (see my work at the end of Issue 18003 for example). On the other hand, removing the existing checks could potentially break someone’s code. I suggest closing this, unless someone has a specific proposal or reason to change.
History
Date User Action Args
2022-04-11 14:57:46adminsetgithub: 62282
2015-11-28 04:49:49martin.pantersetstatus: open -> closed
resolution: not a bug
2015-08-06 03:07:00martin.pantersetnosy: + martin.panter
messages: + msg248096
2015-03-02 01:41:52BreamoreBoysetmessages: + msg237003
2014-06-12 23:07:41BreamoreBoysetnosy: + BreamoreBoy
messages: + msg220396
2013-05-28 17:08:47serhiy.storchakasetnosy: + pitrou, benjamin.peterson, stutzbach, hynek
2013-05-28 16:31:28dwight.guthcreate