This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: isinstance(x, collections.Iterator) can return True, when x isn't iterable
Type: behavior Stage: resolved
Components: Library (Lib) Versions: Python 3.1, Python 3.2, Python 2.7
process
Status: closed Resolution: fixed
Dependencies: Superseder:
Assigned To: belopolsky Nosy List: belopolsky, daniel.urban, rhettinger, stutzbach
Priority: normal Keywords:

Created on 2010-11-28 15:58 by daniel.urban, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Messages (6)
msg122668 - (view) Author: Daniel Urban (daniel.urban) * (Python triager) Date: 2010-11-28 15:58
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 "<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.
msg122702 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2010-11-28 18:55
> A possible solution could be in 
> collections.Iterator.__subclasshook__ 
> checking for both required methods.

That makes sense.  PEP 234 requires
iterators to support both methods.
msg122763 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2010-11-29 03:56
Fixed in r86857.
Needs backport.
msg122861 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2010-11-29 20:03
Alexander, do you want to take care of the backport?
msg122865 - (view) Author: Alexander Belopolsky (belopolsky) * (Python committer) Date: 2010-11-29 20:16
ok
msg122876 - (view) Author: Alexander Belopolsky (belopolsky) * (Python committer) Date: 2010-11-30 01:19
Committed in r86872 (3.1) and r86873 (2.7).
History
Date User Action Args
2022-04-11 14:57:09adminsetgithub: 54774
2010-11-30 01:19:59belopolskysetstatus: open -> closed
resolution: fixed
messages: + msg122876

stage: resolved
2010-11-29 20:16:44belopolskysetmessages: + msg122865
2010-11-29 20:03:11rhettingersetassignee: rhettinger -> belopolsky

messages: + msg122861
nosy: + belopolsky
2010-11-29 03:56:50rhettingersetmessages: + msg122763
versions: + Python 2.7
2010-11-28 18:55:22rhettingersetassignee: rhettinger
messages: + msg122702
2010-11-28 15:58:23daniel.urbancreate