Search code examples
pythonbuilt-in

About the built-in __iter__


I'm learning python and reading fluent python book! While following some class implementation, I stopped by this snippet of code:

def __iter__(self):
    return iter(self._components)

with components being an array of floats, my question is: why calling the iter() method on components although it's already an iterable?.


Solution

  • While the documentation doesn't make it very clear, it is because __iter__ must (not should) return an iterator, not an iterable:

    % python
    Python 3.6.3 (default, Oct  3 2017, 21:45:48) 
    [GCC 7.2.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> class Foo:
    ...     def __iter__(self):
    ...         return []
    ... 
    >>> iter(Foo())
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: iter() returned non-iterator of type 'list'