0

I am aware that there are very good reasons not to force __len__ to be part of the iterators' API (e.g. Understanding len function with iterators) and I do understand that the difference between an Iterable and a Sequence is mostly with the implementation of __len__ (e.g. What exactly does "iterable" mean in Python?).

However, I was wandering if there is a standard way of determining or at least naming "(in)finite" iterators, so that the need for avoiding infinite iterators is at least well-documented.

This would be useful if, for example, the code needs to iterate through all the elements of the Iterable and waiting for the system to run out of memory is not an acceptable behavior for the software.

norok2
  • 25,683
  • 4
  • 73
  • 99
  • I would simply never implement `__len__` if the iterator is infinite. If the iterator can be finite, you can implement `__len__` and raise a `ValueError` in case the iterator has infinite length. The `cycle` of `itertools` does this for instance: it does not implement `__len__`. As a result if `__len__` exists and returns a valid integer, it is guaranteed to be finite. After all, for some sequences it is currently not proven that they are finite. – Willem Van Onsem Sep 22 '17 at 10:56
  • For instance the Collatz conjecture defines a sequence, currently it is unknown if every element results in a finite sequence. – Willem Van Onsem Sep 22 '17 at 10:59
  • Deciding how to implement `__len__` is for when you are implementing your own `Sequence` or `Iterator`. You are right in that `cycle` does not implement `__len__`, but so does any `iterator` whether finite or infinite. The question itself is whether there is a (standard) way of detecting/documenting failure/success for infinite iterators. – norok2 Sep 22 '17 at 11:31

0 Answers0