Issue 36455: collections.abc.Sequence doesn't support reflection/introspection (original) (raw)
Consider:
from collections.abc import *
class DefinitelyNotAList:
def __init__(self, backer):
self.backer = backer
def __getitem__(self, key):
return self.backer[key]
def __len__(self):
return len(self.backer)
def __contains__(self, needle):
return needle in self.backer
def __reversed__(self):
return reversed(self.backer)
def __iter__(self):
return list.__iter__(self.backer)
def index(self, *args, **kwargs): return self.backer.index(*args, **kwargs)
def count(self, *args, **kwargs): return self.backer.count(*args, **kwargs)
dnal = DefinitelyNotAList([2,4,6,8])
for abc in [Collection, Reversible, Sized, Iterable, Container, Sequence]:
print(abc.__name__.ljust(12), isinstance(dnal, abc))
Which prints:
Collection True
Reversible True
Sized True
Iterable True
Container True
Sequence False
I'm not sure whether this is a bug, a docs bug, or just a misunderstanding but my expectation, is that, somehow, I could get isinstance(obj, Sequence) to return without explicitly registering it, just as True is returned for the other abcs.
Edit conflict -- indeed -- self closing.
I should point out that this could be fixed with something like the following:
@classmethod
def __subclasshook__(cls, C):
if cls is Sequence:
return _check_methods(C, "__reversed__", "__iter__",
"__len__", "__contains__", "__getitem__")
return NotImplemented
But seeing as it's not the only abc that is without a subclass hook, I wanted to raise an issue before I submitted a complete PR implementing subclasshooks for the rest of the abcs that need them.