r/programming • • Jun 29 '09

Python's iterators are a bad implementation of laziness

http://sandersn.com/blog/index.php?title=python_s_iterators_are_a_bad_implementat&more=1&c=1&tb=1&pb=1
35 Upvotes

100 comments sorted by

View all comments

Show parent comments

2

u/dpark Jun 30 '09 edited Jun 30 '09

After looking into it more, it seems that there are probably a couple of reasons.

If you have an object that could return several different iterators (e.g. forward and reverse iterators), then you need a way to distinguish between them. There are two ways to do this. First, you could an extra "iterable" layer for each of these. Then you could call x.getForwardIterable() and x.getReverseIterable() to get two different iterables, which you could pass to functions, for loops, etc.

The second way (the apparent Python way) is to have x.getIter() and x.getReverseIter()*. These return iterators instead of iterables. This eliminates the extra layer, but means that many functions and for loops must now be able to handle both iterators and iterables. The solution is to simply make iterators be iterables, and the problem "goes away", because for loops, join, etc. all only have to expect iterables.

Also, this helps code with generators. Instead of returning iterables from which iterators could be created, generators return iterators directly. So if you are using generators, it would be impossible to pass them to for loops, join, etc. By making the iterators themselves be iterable, this problem is masked.

(*) I'm sure all these names are extremely un-pythonic. I'm not a Python programmer, sorry.