Issue 10565: isinstance(x, collections.Iterator) can return True, when x isn't iterable (original) (raw)

If the type of x defines next, but not iter, isinstance(x, collections.Iterator) returns True, but in fact x isn't iterable.

class X: ... def next(self): ... raise StopIteration() ... x = X() isinstance(x, collections.Iterator) True issubclass(X, collections.Iterator) True list(x) Traceback (most recent call last): File "", line 1, in TypeError: 'X' object is not iterable

The reason for this is that collections.Iterator.subclasshook checks for a next method, and if finds one, returns True. (The class provides an iter mixin method, so this doesn't cause problems for classes inheriting collections.Iterator.)

A possible solution could be in collections.Iterator.subclasshook checking for both required methods.