python file API
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Mon Sep 24 22:28:37 EDT 2012
On Mon, 24 Sep 2012 15:36:20 -0700, zipher wrote:
> You raise a valid point: that by abstracting the file pointer into a
> position attribute you risk "de-coupling" the conceptual link between
> the underlying file and your abstraction in the python interpreter
I don't think this argument holds water. With the ease of writing
attributes, it is more likely that people will perform file position
operations directly on file.pos rather than decoupling it into a
variable. Decoupling is more likely with file.seek, because it is so much
more verbose to use, and you get exactly the same lack of bounds checking:
py> f = open("junk", "w") # make a sample file
py> f.write("abcd\n")
py> f.close()
py> f = open("junk") # now do decoupled seek operations
py> p = f.tell()
py> p += 2000
py> p -= 4000
py> p += 2
py> p += 2000
py> f.seek(p)
py> f.read(1)
'c'
But really, who does such a sequence of arithmetic operations on the file
pointer without intervening reads or writes? We're arguing about
something that almost never happens.
By the way, the implementation of this is probably trivial in Python 2.x.
Untested:
class MyFile(file):
@property
def pos(self):
return self.tell()
@pos.setter
def pos(self, p):
if p < 0:
self.seek(p, 2)
else:
self.seek(p)
You could even use a magic sentinel to mean "see to EOF", say, None.
if p is None:
self.seek(0, 2)
although I don't know if I like that.
--
Steven
More information about the Python-list
mailing list