Message from discussion python file API
Received: by 10.180.107.38 with SMTP id gz6mr874138wib.0.1348558140219;
Tue, 25 Sep 2012 00:29:00 -0700 (PDT)
From: Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info>
Subject: Re: python file API
User-Agent: Pan/0.133 (House of Butterflies)
Date: 25 Sep 2012 07:28:59 GMT
Organization: Unlimited download news at news.astraweb.com
Content-Type: text/plain; charset=UTF-8
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):
>> def pos(self):
>> return self.tell()
>> def pos(self, p):
>> if p< 0:
>> self.seek(p, 2)
>> 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
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.