Pre-PEP: reverse iteration methods

Hannu Kankaanpää hanzspam at yahoo.com.au
Wed Sep 24 02:56:21 EDT 2003


"Andrew Dalke" <adalke at mindspring.com> wrote in message news:<w57cb.1289$RW4.1142 at newsread4.news.pas.earthlink.net>...
> Sure.  Then it'll given an exception.  The implementation
> should turn around and raise the proper exception there
> instead of a "len doesn't exist" one.
> 
> There's also a problem that len works on a dict but
> __getitem__(int) will only work if the dict stores 0->n-1
> as keys.


How about using a temporary sequence if __riter__ isn't defined?
It's slow, but would work with all non-infinite iterators that
don't have strange side effects (vast majority).


def riter(obj):
    try:
        rit = getattr(obj, "__riter__")
    except AttributeError:
        # assuming list has __riter__, the following could be:
        # for x in riter(list(obj)):
        #     yield x
        seq = list(obj)
        n = len(seq)
        while n != 0:
            n -= 1
            yield seq[n]
    else:
        for term in rit():
            yield term

# reverse iteration of file
f = file('riter.py')
try:
    for line in riter(f):
        print line,
finally:
    f.close()

# reverse iteration of a dictionary
for x in riter({'foo':1, 'bar':2}):
    print x,


I changed it to use a shorter name as suggested by Reedy, to be similar
with rfind etc. I also prefer a function instead of a method, as the function
can provide (slow) default behaviour for iterators that don't explicitely
support reverse iteration.




More information about the Python-list mailing list