tuples, index method, Python's design

Antoon Pardon apardon at forel.vub.ac.be
Fri Apr 13 03:46:58 EDT 2007


On 2007-04-12, Steven D'Aprano <steve at REMOVE.THIS.cybersource.com.au> wrote:
> On Thu, 12 Apr 2007 07:37:38 +0000, Antoon Pardon wrote:
>
>> I once had a problem I like to solve by having a dictionary
>> where the keys were multidimensional points on an integer grid.
>> For a number of reasons I thought it would be easier if I could
>> use lists, but most people argued that would be a bad idea and
>> that I should use tuples, because they are immutable.
>
> Also because code that raises "TypeError: list objects are unhashable" is
> probably not going to work very well.
>
>
>> Of course if I now would want to find out if the point is on an axis and
>> which axis that is, I cannot use index because that is not available.
>
> If memory is more important to you than speed:
>
> class IndexTuple(tuple):
>     def index(self, target):
>         for i, x in enumerate(self):
>             if x == target: return i
>         raise ValueError
>
> Or if speed is more important to you than memory:
>
> class IndexTuple2(tuple):
>     def index(self, target):
>         return list(self).index(target)
>
> If you prefer not to subclass, you can write an index function:
>
> def index(sequence_or_mapping, target):
>     try:
>         return sequence_or_mapping.index(target)
>     except AttributeError:
>         return list(sequence_or_mapping).index(target)
>
>
> So much fuss over such a little thing... yes it would be nice if tuples
> grew an index method, but it isn't hard to work around the lack.

Yes it is a little thing. But if it is such a little thing why do
the developers don't simply add it?

Python like any other human product has it shortcomings. I can live
with them. If a wart turns up and the general answer would be, yes
we know it is a wart but it is the result of how python grew or
it was the best compromise we could think of and too much depends
on it now to change it.  This kind of threads would die quickly.

Instead we often enough see the warts getting defended as good design.

-- 
Antoon Pardon



More information about the Python-list mailing list