PEP 322: Reverse Iteration (REVISED, please comment)

Peter Otten __peter__ at web.de
Wed Oct 29 20:33:33 CET 2003


Raymond Hettinger wrote:

>> Since iter() constructs and returns a type 'iterator' object, I
>> expected that it might be a type object, just like int(), etc.  If it
>> were turned into one, like int(), etc, have been, then
>  . . .
>> Unless there is a good reason to not make iter a type object, then
>> making it so could be part of the suggested implementation of the PEP.
> 
> iter() is a factory function that can return all kinds of things:
> 
>>>> from random import random
>>>> iters = iter('str'), iter(['list']), iter(dict(a=1)), iter(random,
>>>> None) map(type, iters)
> [<type 'iterator'>, <type 'listiterator'>, <type 'dictionary-iterator'>,
> [<type
> 'callable-iterator'>]

So why couldn't all these iterators inherit from iter just as unicode and
str do from basestring?

> Let's see if we can get back to the merits of the pep.

I respect that you want to keep this discussion focused, and itertools is my
favourite new package - but sometimes il faut reculer pour mieux sauter :-)

> Looking at your own code, can you verify that ireverse()
> is an improvement over what you have now.

While I'm zipping and enumerating all the time, reversing is rare, so I'm
not desperately awaiting this builtin.
The most common usecase seems iteration over a sequence that is mutated in
the process:

class mutate(object):
    def __init__(self, alist):
        self.index = -1
        self.alist = alist
    def next(self):
        self.index += 1
        try:
            self.alist[self.index]
        except IndexError:
            raise StopIteration
        return self
    def value(self):
        return self.alist[self.index]
    def __iter__(self):
        return self
    def delete(self):
        del self.alist[self.index]
        self.index -= 1

sample = range(10)
for item in mutate(sample):
    if item.value() in [3,5,7]:
        item.delete()
print sample

I'm sure that the above approach can be improved (in particular, it must not
rely on an index, i. e. random access) as I'm sure that it makes the
coder's intention clearer than the "reverse to enable deletion" idiom.

Peter






More information about the Python-list mailing list