Thomas Jollans <t...@tjol.eu> added the comment:

Hello Xiang Zhong,

You're almost correct, but not quite.

File descriptors/file numbers are just integers assigned by the operating 
system, and Python has little to no control over them. The OS keeps a numbered 
list of open files for each process, and Python can make system calls like 
"read 10 bytes from file 5" or "write these 20 bytes to file 1".

Also good to know: 0 is stdin, 1 is stdout, 2 is stderr, 3+ are other files.

Now, what happens:

# Python asks the OS to open a new file. The OS puts the new file on
# the list and gives it the lowest number that is not in use: 3.
fd = tempfile.TemporaryFile()
# fd is an file object for file no 3
with open(fd.fileno()) as f:
    # f is another object for file no 3
    pass             # I know fd is closed after with is done
# the with statement closes file no 3
# fd does not know that file no 3 is closed. (and has no way of knowing!)

# Python asks the OS to open a new file. The OS puts the new file on
# the list and gives it the lowest number that is not in use: 3.
_tmp = tempfile.TemporaryFile()
# A new temporary file object is created for file no 3
fd = _tmp
# The old fd is finalized. It still thinks it has control of file
# no 3, so it closes that. The new temporary file object is given
# the name fd.


Aside: f.fileno() is not more "advanced" than f.name. It's just that, in the 
case of tempfile.TemporaryFile, the file is immediately deleted and ends up 
having no name, so f.name falls back on returning the file number. I just 
preferred it here to be explicit about what's going on. Normally f.name would 
be a string (and it is for a TemporaryFile on Windows!); here, it's an int.

----------

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue44013>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to