R
Roy Smith
There is no sensible use-case for creating a file OBJECT unless it
initially wraps an open file pointer.
OK, I guess that's a fair statement. But mostly because a python file
object only exposes those subset of operations you can do on file
descriptors which deal with reading and writing the contents of a
file.
It would not be true if python file objects included methods for
querying and manipulating file metadata. It's not hard to imagine a
file class which could be used like:
f = file("/path/to/my/file")
f.delete()
That would be a totally different model from the current python file
object. And then there would be plenty of things you might want to do
to a file other than open it...
file("/path/to/my/directory").chdir()
file("/dev/sdf").mount("/var/lib/whatever")
file("/mnt/swapfile").swapon()
The standard C I/O library doesn't support creating a file
descriptor unless it is a file descriptor to an open file [...]
there is no corresponding function to create a *closed* file
description. (Because such a thing would be pointless.)
What about sockets? From the python standard library:
s = socket.socket()
Now what? You can't do much with your shiny new socket until you call
bind() or connect(), or a few other things. At least not for TCP.
This is essentially the two-phased construction pattern. Of course,
the python socket module just exposes the semantics of the underlying
OS sockets, so there's not a lot of choice there.