You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
isinstance(x, collections.Iterator) can return True, when x isn't iterable #54774
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
assignee='https://github.com/abalkin'closed_at=<Date2010-11-30.01:19:59.192>created_at=<Date2010-11-28.15:58:23.020>labels= ['type-bug', 'library']
title="isinstance(x, collections.Iterator) can return True, when x isn't iterable"updated_at=<Date2010-11-30.01:19:59.190>user='https://github.com/durban'
If the type of x defines __next__, but not __iter__, isinstance(x, collections.Iterator) returns True, but in fact x isn't iterable.
>>> classX:
... def__next__(self):
... raiseStopIteration()
...
>>> x = X()
>>> isinstance(x, collections.Iterator)
True
>>> issubclass(X, collections.Iterator)
True
>>> list(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
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.
Activity
durban commentedon Nov 28, 2010
If the type of x defines __next__, but not __iter__, isinstance(x, collections.Iterator) returns True, but in fact x isn't 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.
rhettinger commentedon Nov 28, 2010
That makes sense. PEP-234 requires
iterators to support both methods.
rhettinger commentedon Nov 29, 2010
Fixed in r86857.
Needs backport.
rhettinger commentedon Nov 29, 2010
Alexander, do you want to take care of the backport?
abalkin commentedon Nov 29, 2010
ok
abalkin commentedon Nov 30, 2010
Committed in r86872 (3.1) and r86873 (2.7).