why does isinstance check for abc.Sequence return False for custom classes?
I had a similar question today.
From what I can gather, collections.abc.Iterable
implements a custom __subclasshook__()
method, whereas collections.abc.Sequence
does not:
# _collections_abc.py
class Iterable(metaclass=ABCMeta):
__slots__ = ()
@abstractmethod
def __iter__(self):
while False:
yield None
@classmethod
def __subclasshook__(cls, C):
if cls is Iterable:
return _check_methods(C, "__iter__") # True if __iter__ implemented
return NotImplemented
What this means is that if a class Foo
defines the required __iter__
method then isinstance(Foo(), collections.abc.Iterable)
will return True
:
from collections.abc import Iterable
class Foo:
def __iter__(self):
return []
assert isinstance(Foo(), Iterable)
I'm not sure why collections.abc.Iterable
implements a custom __subclasshook__()
method but collections.abc.Sequence
does not.