Advertisement
Intermediate Python, Iterators & the Iterator Protocol

How does Python know whether to treat a for-in target as iterable, and what error occurs if it isn't?

Short answer

The for-loop calls iter() on the target, which invokes __iter__(). If the object has no __iter__ (and, as a fallback, no __getitem__ supporting integer indexing from 0), Python raises TypeError: 'X' object is not iterable.

Save Python mock interview
Advertisement
AModel answer
The for-loop calls iter() on the target, which invokes __iter__(). If the object has no __iter__ (and, as a fallback, no __getitem__ supporting integer indexing from 0), Python raises TypeError: 'X' object is not iterable. This is why custom classes need __iter__ (or, historically, __getitem__) to support iteration.
class NoIter:
    pass

try:
    for x in NoIter():
        pass
except TypeError as e:
    print(e)  # 'NoIter' object is not iterable
Real-world example
A bug report of 'object is not iterable' on a custom API response wrapper leads to adding __iter__ that delegates to an internal list attribute.
Likely follow-ups
  • What is the old-style __getitem__ iteration protocol?
  • How does isinstance(x, collections.abc.Iterable) check for this?
Related topics