tuples, index method, Python's design

Antoon Pardon apardon at forel.vub.ac.be
Tue Apr 10 18:53:19 CEST 2007


On 2007-04-10, Carsten Haese <carsten at uniqsys.com> wrote:
> On Tue, 2007-04-10 at 13:21 +0000, Antoon Pardon wrote:
>> >  But if you are so eager to rewrite, how about the following:
>> > 
>> > I am using the struct module to get binary data from a file.
>> > Sometimes I want to skip until I find a particular binary
>> > number. Somewhat simplified it looks like this:
>> > 
>> > 
>> > class Itemfile:
>> >   def __init__(self, fn):
>> >     self.fl = open(fn)
>> >     self.ix = 80
>> > 
>> >   def nextitem(self):
>> >     if self.ix == 80:
>> >       self.buf = struct.unpack("80i", self.fl.read(320))
>> >       self.ix = 0
>> >     result = self.buf[self.ix]
>> >     self.ix += 1
>> >     return result
>> > 
>> >   def skipuntil(self, val):
>> >     done = False
>> >     while not done:
>> >       try:
>> >         self.ix = self.buf.index(val, self.ix)
>> > 	done = True
>> >       except ValueError:
>> >         self.ix = 0
>> > 	self.buf = struct.unpack("80i", self.fl.read(320))
>> > 
>> > 
>> > Now I'm sure you can rewrite this without the need of tuple.index.
>> > It just seems odd that I have to go through extra hoops here to
>> > get the effect of tuple.index because struct.unpack returns its result
>> > in a tuple and a tuple doesn't provide index.
>
> Your data is an array. Choosing a data structure that doesn't fit your
> data is always going to cause pain. Instead of using struct.unpack, you
> should use array.array, and voila!, you get an index method.

No it is not. This is exactly what I thought was going to happen. One
simplifies a problem so that the code is not too big to discuss here
and people will use characteristics of the simplified code to suggest
how one should have solved the problem differently.

I'm not interrested in going through such a merry around again.

As I said, writing an index function that works with any kind
of sequence is easy enough and once written can be used as
often as one whishes. So although I prefer more consistency
from a language that python currently provides the language
has enough going for it to stick with it dispite these kind
of warts. So having that function is a practical enough solution
for me. And curiously, having that function makes using
tuples no longer painfull in situations where other would
argue that tuples don't fit my data. If tuples don't fit
my data, I sure find it strange that one little function
causes you to no longer experience it as such.

-- 
Antoon Pardon



More information about the Python-list mailing list