python file API
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Tue Sep 25 03:28:59 EDT 2012
On Tue, 25 Sep 2012 07:25:48 +0200, Thomas Rachel wrote:
> Am 25.09.2012 04:28 schrieb Steven D'Aprano:
>
>> 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.
>
> The whole concept is incomplete at one place: self.seek(10, 2) seeks
> beyond EOF, potentially creating a sparse file. This is a thing you
> cannot achieve.
On the contrary, since the pos attribute is just a wrapper around seek,
you can seek beyond EOF easily:
f.pos = None
f.pos += 10
But for anything but the most trivial usage, I would recommend sticking
to the seek method.
The problem with this idea is that the seek method takes up to three
arguments (the file being operated on, the position, and the mode), and
attribute syntax can only take two (the file, the position, e.g.:
file.pos = position). So either there are cases that file.pos cannot
handle (and so we need to keep tell/seek around, which leaves file.pos
redundant), or we need multiple attributes, one for each mode), or we
build a complicated, inconvenient API using special data types instead of
plain integers.
So all up, I'm -1 on trying to replace the tell/seek API, and -0 on
adding a second, redundant API.
Wait, there is another alternative: tuple arguments:
f.pos = (where, whence)
being the equivalent to seek(where, whence). At this point you just save
two characters "f.pos=a,b" vs "f.seek(a,b)" so it simply isn't worth it
for such a trivial benefit.
--
Steven
More information about the Python-list
mailing list