tuples, index method, Python's design

Antoon Pardon apardon at forel.vub.ac.be
Tue Apr 10 09:21:03 EDT 2007


On 2007-04-10, Carsten Haese <carsten at uniqsys.com> wrote:
> On 10 Apr 2007 09:48:41 GMT, Antoon Pardon wrote
>> If someone states: "Show me your use case for using tuple.index and I
>> will show you how to avoid it." or words to that effect I think there
>> is little use trying.
>
> Or maybe you just can't think of any good use cases, and that's annoying you
> because it proves my point. Please, prove me wrong by showing use cases for
> tuple.index that can't be rewritten.

No you just have proven my point. I predicted that whatever use case
would be given, people would stand ready to rewrite is and use those
rewritals as argument againt the use case. Here you are ready to do
just that.

Since you can just write an index function that works with any sequence
or you could simply write something like list(tup).index('...'), any
code that would use tupple.index can be rewritten to do without.

But that is not such a strong argument. Should the case be reversed
and tuples have an index method and lists not, you would be able
to rewrite any code that would use list.index into code that
wouldn't. 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.

-- 
Antoon Pardon



More information about the Python-list mailing list