Customize the effect of enumerate()?

Dustan DustanGroups at gmail.com
Mon Oct 23 13:43:40 CEST 2006


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?

I'm not 'expecting' anything to reach that clause, but it is a good
catch-all if I forget something or have a bug somewhere.

> > 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.
>
> You can write your own enumerate function and then bind that to the
> name 'enumerate'.

Except that my program is supposed to be treated as a module with tools
to do certain things. I certainly can't control whether a 3rd party
programmer uses "import myModule" or "from myModule import *".

I haven't gotten around to doing it yet, but I'm pretty sure I'm
planning on taking Paul Rubin's course of action - make a method
(iteritems or similar) that will enumerate correctly.




More information about the Python-list mailing list