Customize the effect of enumerate()?

Dustan DustanGroups at gmail.com
Sat Oct 21 02:45:19 CEST 2006


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)

Why the funny behavior, you ask? For my class A, it doesn't make sense
to number everything the standard programming way. Of course, if
someone uses enumerate, it's going to number the items the same way as
ever. Is there any way to modify that behavior, any special function to
set? There doesn't appear to be, according to the docs, but it never
hurts to make sure.




More information about the Python-list mailing list