Robert Xiao <nneon...@gmail.com> added the comment:
Could this be solvable if `closefd` were a writable attribute? Then we could do file = None try: file = io.open(fd, ..., closefd=False) file.closefd = True except: if file and not file.closefd: os.close(fd) raise I believe this should be bulletproof - a KeyboardInterrupt can happen anywhere in the `try` and we will not leak or double-close. Either file.closefd is set, in which case `file` owns the fd and will close it eventually, or file.closefd is not set in which case the fd needs to be manually closed, or file doesn't exist (exception thrown in io.open or while assigning file), in which case the fd still needs to be manually closed. Of course, this can leak if a KeyboardInterrupt lands in the `except` - but that's not something we can meaningfully deal with. The important thing is that this shouldn't double-close if I analyzed it correctly. This is a somewhat annoying pattern, though. I wonder if there's a nicer way to implement it so we don't end up with this kind of boilerplate everywhere. ---------- _______________________________________ Python tracker <rep...@bugs.python.org> <https://bugs.python.org/issue39318> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com