[Python-ideas] Previous item from iterator.

Todd toddrjen at gmail.com
Wed Apr 15 18:36:59 CEST 2015


On Wed, Apr 15, 2015 at 6:26 PM, Krystian Kichewko <
krystiankichewko at gmail.com> wrote:

> Hi all!
>
> I hope I'm posting in correct place.
>
> I would like to propose an idea for iterating over an iterator in reverse.
>
> prev(iterator[, default])
>
> Built-in function: it should retrieve previous element from an
> iterator by calling its __prev__() method.
>
>
> Add new, optional method to iterator protocol:
>
> __prev__()
>
> This method should return previous element from iterator or raise
> StopIteration exception if the is no previous element.
>
>
> This should be optional, because it would be hard to implement this
> behaviour in some iterators (e.g. It would be hard to do this for file
> iterator that returns lines). Other iterators should be modified to
> include __prev__() (e.g. itertools.count(), list iterator).
>
> If an iterator doesn't support prev TypeError should be raise when
> prev is called.
>
> Please let me know what you think about this? If there are no obvious
> problems I will write a PEP for this.
>
> Thanks,
> Krystian Kichewko
>
> ps. I've tried searching for this idea on python-ideas and couldn't
> find anything. If I missed it and my email is a duplicate, sorry.
>


What is the use-case for this?  If the iterator can go both directions,
what is the case where this would be useful but an object with an index,
like a list, wouldn't be?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150415/c09e72a9/attachment-0001.html>


More information about the Python-ideas mailing list