[Python-ideas] Previous item from iterator.

Krystian Kichewko krystiankichewko at gmail.com
Wed Apr 15 18:26:50 CEST 2015


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.


More information about the Python-ideas mailing list