collections.abc Types Drive isinstance Checks
collections.abc classes answer isinstance for any object exposing the right protocol, and Sequence.register accepts unrelated classes as virtual subclasses.
Code
from collections.abc import Mapping, Sequence
# collections.abc 的抽象类型可以直接做 isinstance 判断,不用自己数方法
print("list is Sequence :", isinstance([1, 2], Sequence))
print("dict is Mapping :", isinstance({"a": 1}, Mapping))
print("str is Sequence :", isinstance("ab", Sequence))
print("int is Sequence :", isinstance(42, Sequence))
# 没继承也能注册成虚拟子类:isinstance 照样放行
class Stack:
def __init__(self):
self.items = []
def __getitem__(self, index):
return self.items[index]
def __len__(self):
return len(self.items)
print("before register :", isinstance(Stack(), Sequence))
Sequence.register(Stack)
print("after register :", isinstance(Stack(), Sequence))
# 判断能力而非继承:抽象基类声明的是"最小方法集"的契约
import collections.abc as cabc
print("Container checks :", isinstance([1], cabc.Container), isinstance({1}, cabc.Container))What the code does
Count the class Stack and the functions __init__, __getitem__ and __len__ as the entire surface area of collections.abc Types Drive isinstance Checks.
Using it
Entry signature: def __init__(self)
Each run prints the 7 labeled blocks list is Sequence :, dict is Mapping :, str is Sequence :, int is Sequence :, before register :, after register :, Container checks : in source order.
Key statements
def __getitem__(self, index):
return self.items[index]
def __init__(self):
self.items = []
def __len__(self):
return len(self.items)
Interactive Tools for This Topic
FAQ
- Do I need to install anything before running this?
- No — every API used here ships with the language runtime, so there is nothing to install. Every import resolves inside the standard library — `collections.abc`. The file defines `__init__`, `__getitem__`, `__len__` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.