Pre-PEP: reverse iteration methods

Peter Otten __peter__ at web.de
Wed Sep 24 20:46:16 CEST 2003


Raymond Hettinger wrote:

>   * It behaves badly with infinite iterators as inputs

[...]

> def ireverse(obj):
>     assert not hasattr(obj, 'keys')
      
      # let inifinite iterators identify themselves     
      assert not hasattr(obj, 'infinite') 

>     try:
>         for i in xrange(len(obj)-1, -1, -1):
>             yield obj[i]
>     except (AttributeError, TypeError):
>         x = list(obj)   # XXX fails with infinite iterators
>         x.reverse()
>         for elem in x:
>             yield elem

As infinite iterators are rare, it would not be too cumbersome to let them
identify themselves as such.

Peter




More information about the Python-list mailing list