I think a slightly better solution would be to raise a TypeError rather than a plain exception (this is what normally happens with a non-iterable class:
class A(object):
# show what happens with a non-iterable class with no __getitem__
pass
class B(object):
def __getitem__(self, k):
return k
def __iter__(self):
raise TypeError('%r object is not iterable'
% self.__class__.__name__)
Testing:
>>> iter(A())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'A' object is not iterable
>>> iter(B())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "iter.py", line 9, in __iter__
% self.__class__.__name__)
TypeError: 'B' object is not iterable