bpo-18748: io.IOBase destructor now logs close() errors in dev mode by vstinner · Pull Request #12786 · python/cpython

Example with bug.py from https://bugs.python.org/issue18748#msg339979.

Without the change.

$ ./python bug.py 
libgcc_s.so.1 must be installed for pthread_cancel to work
Aborted (core dumped)

... Python silently ignores the EBADF error on close(3) causing weird bug which calls abort() and creates a coredump :-( Or sometimes, you are lucky and nothing happens. Example with -X dev (but without my change):

$ ./python -X dev bug.py 
bug.py:28: ResourceWarning: unclosed file <_io.TextIOWrapper name='a.txt' mode='w+' encoding='UTF-8'>
  main()
ResourceWarning: Enable tracemalloc to get the object allocation traceback

ResourceWarning isn't the real bug here, it's more ore less fine to rely on Python to automatically close files usually.

With the change.

$ ./python -X dev bug.py 
bug.py:28: ResourceWarning: unclosed file <_io.TextIOWrapper name='a.txt' mode='w+' encoding='UTF-8'>
  main()
ResourceWarning: Enable tracemalloc to get the object allocation traceback
Exception ignored in: <_io.TextIOWrapper name='a.txt' mode='w+' encoding='UTF-8'>
OSError: [Errno 9] Bad file descriptor

The interesting part is the new exception which contains the filename a.txt, useful to identify the bug, and the exception: OSError: [Errno 9] Bad file descriptor.