python duration of a file object in an argument list

Posted by msw on Stack Overflow See other posts from Stack Overflow or by msw
Published on 2010-03-23T01:33:30Z Indexed on 2010/03/23 1:41 UTC
Read the original article Hit count: 360

Filed under:
|
|

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 returned 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?

© Stack Overflow or respective owner

Related posts about python

Related posts about file-object