Customize the effect of enumerate()?

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Mon Oct 23 08:53:06 EDT 2006


On Sun, 22 Oct 2006 15:56:16 -0700, Simon Forman wrote:

> Dustan wrote:
>> Can I make enumerate(myObject) act differently?
>>
>> class A(object):
>> 	def __getitem__(self, item):
>> 		if item > 0:
>> 	            return self.sequence[item-1]
>> 	        elif item < 0:
>> 	            return self.sequence[item]
>> 	        elif item == 0:
>> 	            raise IndexError, "Index 0 is not valid."
>> 	        else:
>> 	            raise IndexError, "Invalid Index."
>> 	def __iter__(self): return iter(self.sequence)
> 
> That final else clause is a little funny...    What kind of indices are
> you expecting that will be neither less than zero, greater than zero,
> or equal to zero?

Possible a NaN value? Maybe a class instance with strange comparison
methods?

Personally, I don't like the error message. "Invalid index" doesn't really
tell the caller what went wrong and why it is an invalid index. If I were
programming that defensively, I'd write:

if item > 0:
    return self.sequence[item-1]
elif item < 0:
    return self.sequence[item]
elif item == 0:
    raise IndexError, "Index 0 is not valid."
else:
    print repr(item)
    raise ThisCanNeverHappenError("Congratulations! You've discovered "
    "a bug that can't possibly occur. Contact the program author for "
    "your reward.")

I know some programmers hate "Can't happen" tests and error messages, but
if you are going to test for events that can't possibly happen, at least
deal with the impossible explicitly!


-- 
Steven.




More information about the Python-list mailing list