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

Victor Stinner victor.stinner at haypocalc.com
Sat Nov 1 01:08:09 CET 2008


> Rightnow close() doesn't do anything and you can still write 
> or read after close(). This behavior is surprising to the user.
> I like to change close() to set the internal fd attribute 
> to -1 (meaning close) but keep the fd open.

Let take an example:
-------------------
passwd = open('/etc/passwd', 'rb')

readonly = open(passwd.fileno(), closefd=False)
print("readonly: {0!r}".format(readonly.readline()))
# close readonly stream, but no passwd
readonly.close()
try:
    readonly.readline()
    print("ERROR: read() on a closed file!")
except Exception as err:
    # Expected behaviour
    pass

# passwd is not closed
print("passwd: {0!r}".format(passwd.readline()))
passwd.close()
-------------------

The current behaviour is to accept read/write on a closed file. Sorry 
benjamin, but it's not a feature: it's a bug :-) and passwd.readline() works.

I wrote a patch to implement your suggestion crys and it works as expected: 
when readonly stream is closed, read is blocked but passwd.readline() still 
works. I will attach my patch to the issue 4233.

Victor


More information about the Python-3000 mailing list