tuples, index method, Python's design

Chris Mellon arkanes at gmail.com
Tue Apr 10 14:04:18 EDT 2007


On 4/10/07, Carsten Haese <carsten at uniqsys.com> wrote:
> On Tue, 2007-04-10 at 19:21 +0200, BJörn Lindqvist wrote:
> > On 4/10/07, Carsten Haese <carsten at uniqsys.com> wrote:
> > > > > opponents = tuple(x for x in p if x is not current_player)
> > > > >
> > > > Your alternative is wrong because it wont raise ValueError if
> > > > current_player is not present in the tuple. Please revise your
> > > > "solution."
> > >
> > > You have a point. Here is my revised solution:
> > >
> > > assert current_player in p
> > > opponents = tuple(x for x in p if x is not current_player)
> > >
> > > The added advantage is that AssertionError is better than IndexError for
> > > conveying that a severe program bug has occurred.
> >
> > Assertions are not checked when you run scripts with -O.
>
> Right. Which is why you use assert to guard against situations that
> should never happen, and you determine in unit tests that they, in fact,
> don't happen. Realistically, in a game loop such as
>
> while not game_has_ended:
>   for current_player in p:
>     player_does_something(current_player)
>

I'm curious why someone would even consider using a tuple in this case
regardless. I think that much of the desire for tuple.index is because
people use a tuple where they could have a list, but either a) some
vestige of B&D language programming comes out and they want to make
sure a caller can't mutate it or b) they decide it's not going to
change and use the "immutable list" version of the tuple.

The first reason is clearly perverse, and can be discounted.

The second means this is not so much about tuple.index as it is about
appropriate data types. It's not going to be resolved by use cases,
because clearly the only use of tuple.index is when you're using it as
an immutable list, as in this case. Any use case where you'd want to
search a tuple can be rewritten (trivially) as a list.

So the solution for the dissenters is to justify the need for a frozen
list, not to justify index on tuples.

The only use case which even approaches reasonableness in this thread
is the binary parsing example (where the position of a value in an
unpacked binary blob might be something you need to know). This is a
rare enough use case and is easy enough to work around (convert it to
a list, write a helper function) that I don't think it's worth any
language change overhead at all.



More information about the Python-list mailing list