In the pickle module documentation there is a snippet of example code:
reader = pickle.load(open('save.p', 'rb'))
which upon first read looked like it would allocate a system file descriptor, read its contents and then "leak" the open descriptor for there isn't any handle accessible to call close()
upon. This got me wondering if there was any hidden magic that takes care of this case.
Diving into the source, I found in Modules/_fileio.c that file descriptors are closed by the fileio_dealloc() destructor which led to the real question.
What is the duration of the file object used by the example code above? After that statement executes does the object indeed become unreferenced and therefore will the fd be subject to a real close(2)
call at some future garbage collection sweep? If so, is the example line good practice, or should one not count on the fd being released thus risking kernel per-process descriptor table exhaustion?