The Python Oracle

python: where is a true built-in file object required?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Magical Minnie Puzzles

--

Chapters
00:00 Python: Where Is A True Built-In File Object Required?
00:32 Answer 1 Score 0
00:45 Answer 2 Score 2
01:07 Accepted Answer Score 3
02:07 Thank you

--

Full question
https://stackoverflow.com/questions/6012...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #api #file #interface #standardlibrary

#avk47



ACCEPTED ANSWER

Score 3


As the other answers have noted, there isn't really anywhere that specifically needs a file object, but there are interfaces that need real OS level file descriptors, which file-like objects like StringIO can't provide.

The os module has several methods that operate directly on file descriptors, as do the select and mmap modules. Some higher level modules rely on those under the hood, so may exhibit some limitations when working with file-like objects that don't support the fileno() method.

I'm not aware of any consistent documentation of these limitations, though (aside from the obvious one of APIs that accept numeric file descriptors rather than objects). It's more a matter of "try it and see if it works". If things don't work, then this is something to keep in the back of your mind to check as a possible culprit (especially if phrases like "no attribute named 'fileno'" or "invalid file descriptor" appear in any relevant error messages).




ANSWER 2

Score 2


Things in the subprocess module need a file object with a fileno callable attribute for stdin, stdout and stderr, which only files with a file descriptor (real files) should implement. isatty() should also be implemented only in real files, but I don't know where it is needed.




ANSWER 3

Score 0


For example, f.fileno() doesn't necessarily return a true OS-level file descriptor that you could use with os.read().