tuples, index method, Python's design

Carsten Haese carsten at uniqsys.com
Tue Apr 10 13:38:02 EDT 2007


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)

it's obvious that the assertion "current_player in p" will never fail.

> Furthermore,
> changing the exception type and the message it produces, is quite a
> big deviation from list.index.

What's your point? I wasn't talking about coding a drop-in replacement
for list.index. I was suggesting one possible solution to a problem that
may or may not be solved by using tuple.index.

-Carsten





More information about the Python-list mailing list