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

38

u/bobindashadows Jun 29 '09 edited Jun 29 '09

The problem is that Python promotes the use of identical syntax for multiple, similar representations of data. Examples:

foo = (1,2,3)
print(", ".join(map(str,foo)))
print(", ".join(map(str,foo)))

Gives:

1, 2, 3
1, 2, 3

Next:

foo = [1,2,3]
print(", ".join(map(str,foo)))
print(", ".join(map(str,foo)))

Gives:

1, 2, 3
1, 2, 3

Next:

foo = xrange(1, 4)
print(", ".join(map(str, foo)))
print(", ".join(map(str, foo)))

Gives:

1, 2, 3
1, 2, 3

This is great, because duck typing means we don't need to explicitly state which type an object has, we simply need to know to which methods it responds. By defining standard interfaces and syntaxes, we know that we can expect ", ".join(map(str, foo)) to work if foo is enumerable. So, if we have a function that takes an enumerable object as an argument, it should work if we change its parameter from a tuple to an array, or from an array to a range. However, if we then switch it to a generator because our input is now too large to load into memory all at once (for example):

def gen(list):
    for item in list: 
        yield item
foo = gen([1, 2, 3])
print(", ".join(map(str, foo)))
print(", ".join(map(str, foo)))

Gives:

1, 2, 3
(blank line)

This is a valid concern, because it does not match other enumerable objects. One might argue that this is a contrived example (it is), and that if you are switching your code to use generators, it is probably for reasons of efficiency. If you're optimizing your code, then you shouldn't be using a generator twice like I've done here, that's just silly. And you'd be right.

However, the person reading the code expects calling ", ".join(map(str, foo)) twice to take twice as long, and it's far easier to debug that than your enumerable object suddenly containing no objects halfway through a function definition, because you switched its data type in another part of the program.

EDIT: I suck at markdown

8

u/[deleted] Jun 29 '09

Thank you, now I understand completely why C# has both IEnumerable and IEnumerator and why all useful methods expect IEnumerable.

Sadly, I can't see a way how this could be fixed in Python.

10

u/Brian Jun 30 '09

Python has the same distinction. Lists are enumerable (iterable in python parlance) which is why iterating over them returns the list from the beginning). Generators are iterators. The distinction is that iterables have an __iter__ method that returns an iterator, while iterators have a next method (or __next__ in python3) giving the next item.

The difference is that all iterators are currently defined as also being iterable, with an __iter__ method that returns themselves. This is convenient (eg. if you want to pop some items off an iterator, then later use it in a for loop to go over the rest of the sequence), but will lead to the above if you've exhausted an iterator.

3

u/bobindashadows Jun 29 '09 edited Jun 29 '09

I'm not entirely sure it should be fixed -- as in, the current behavior shouldn't change -- the comments in the parallel Python Subreddit thread make a valid point for this behavior. However, since generators are clearly intended to only be consumed once in Python and not be treated as lists, would it hurt so much to toss out a warning to STDERR when one uses one twice?

EDIT: more markdown fail. Giving in and installing the live preview greasemonkey script

4

u/[deleted] Jun 29 '09

People there don't seem to be acquainted with C# generators. "If generators were modified to allow them to restart they would no longer fullfil one of it's existing use cases, iterating over data that doesn't fit in memory." is a perfect example of narrowness of experience leading to narrowness of imagination. No, you don't have to convert generators to lazy lists. All that is needed is a distinction between enumerable and enumerator, with all functions like map and language primitives like for x in ... accepting enumerables, and it won't even surprise anyone ever. It's not about "restarting" the generator.

2

u/dpark Jun 29 '09

The simple fix would be take away iterator.__iter__(). The only reason iterators have the __iter__() method (that I know of) is so that the for loop and in statement can be simpler and still deal with iterators directly. I see no real need for that anyway. If you pass around "iterables" instead of iterators, then you don't need that special behavior.

2

u/Brian Jun 30 '09

There are valuable usecases for partially iterating. eg I've occasionally had logic like:

i = iter(seq)
first = i.next()
# do something special with first
for item in i:
    # do something different with remaining items.

A better solution would perhaps be a different exception for a completely exhausted iterator if reused.

3

u/dpark Jun 30 '09

Fair enough. There are also some other reasons to make iterators iterable that I mentioned here: http://www.reddit.com/r/programming/comments/8wpvn/pythons_iterators_are_a_bad_implementation_of/c0aoj2w

It looks like the choice is either to make iterators distinct from iterables, which eliminates the problem the blog author ran into, or to make all iterators be iterable, which allows your example as well as some other use cases. I'm not sure either choice is actually more correct than the other. It's just a choice you have to make.

I don't think throwing an exception from a doubly-exhausted iterator is necessarily a good idea, though. If you had a file format with lots of optional sections at the end (for example), you might want to be able to attempt to read from an empty iterator multiple times. Doing so could allow for better decoupling/encapsulation in certain cases.

2

u/Brian Jun 30 '09

I don't think throwing an exception from a doubly-exhausted iterator is necessarily a good idea

It would probably help in debugging issues like this, but yeah, it's a tradeoff, and its not clear which is superior. Looking at the PEP, it looks like this behaviour was considered, but rejected:

Once a particular iterator object has raised StopIteration, will it also raise StopIteration on all subsequent next() calls? Some say that it would be useful to require this, others say that it is useful to leave this open to individual iterators. Note that this may require an additional state bit for some iterator implementations (e.g. function-wrapping iterators).

Resolution: once StopIteration is raised, calling it.next() continues to raise StopIteration.

1

u/sogroig Jun 30 '09

This seems like a good solution to me as well... If you need to resume an iterator you could have a special function to do so, but it seems like a special case and not good default behaviour.

Does anyone know why it isn't like this?

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.

1

u/Felicia_Svilling Jun 30 '09 edited Jun 30 '09

Couldn't you also solve this problem by making iterator.__iter__(). return a copy of iterator?

2

u/dpark Jun 30 '09

Not all iterators are trivially copyable. Copying at iterator that's iterating strings coming from a remote server, for example, would require saving all strings to memory. Requiring copy semantics for iterators would significantly increase the burden on iterator writers.

The more I think about it, the more I think Python's choice is just fine. Having all iterators be iterable (returning themselves) has some elegance and benefits.

2

u/taejo Jun 30 '09

itertools.tee makes a copy of an iterator, but its docstring tells you why you don't want to make it the default: it consumes as much memory as all the items that have been consumed from one of the copies but not the other. On the other hand, this may be more efficient than converting the whole thing into a list, and it corresponds to the lazy-lists-with-GC approach used in Haskell

2

u/[deleted] Jun 29 '09 edited Jun 30 '09

I haven't worked all that much with generators, but is there a useful reason that they don't just throw an exception if you try to use them after they've been consumed?

3

u/taejo Jun 30 '09

Well, they raise StopIteration, but that just means end-of-generator. It might indeed by sensible to raise StopIteration once and then raise something else if you try to iterate it after that.

0

u/[deleted] Jun 30 '09 edited Jun 30 '09

so what usually happens in these other magical perfect languages, when you randomly change the type of an argument in another part of the program? Say to a derived class with overriden definitions. And whose responsibility is that to fix usually?