Iterators in Python


class Thing:
  ...
  def __iter__(self):
   ...


class ThingIterator:
  ...
  def __iter__(self):
   return self
  def next(self):
   ...
Not only does Python have iterators, it has an interface for them. Things which can be interated must have the __iter__() method, which returns an object having __iter__() and next(). __iter__() returns itself, which next() returns the next element in the iteration. It throws an exception when it's at the end, which I'm not entirely convinced about. Any pair of classes/objects fulfilling this little contract can be used in, through the magic dynamic, squishy duck-typing in a Python for loop or list comprehension. An iterator has __iter__() so it can be used in for loops and list comprehensions in the same way as its containers.

Note the slightly wacky names - the leading/trailing double underscore indicates this is a "special method", ie a method generally used by the language rather than the programmer. (Other include __str__, __lt__ and other ordering, __cmp__, __hash__, __call__ (function call operator), __getitem__ and __setitem__ for indexing, etc). I don't understand why __iter__ is special, but next isn't.

I'll note in passing that this kind of blurring of the language/library boundary makes me a little uncomforable.

Python has iterators, but you're not really supposed to see them.