Advertisement
Advanced Python, Metaclasses & Class Customization

How does __instancecheck__ and __subclasscheck__ on a metaclass enable 'virtual subclassing' as used by collections.abc?

Short answer

ABCMeta overrides __instancecheck__ and __subclasscheck__ so that `isinstance(obj, SomeABC)` can return True even if the object's class never explicitly inherited from SomeABC, as long as it was registered via `SomeABC.register(OtherClass)` or structurally satisfies the ABC's…

Save Python mock interview
Advertisement
AModel answer
ABCMeta overrides __instancecheck__ and __subclasscheck__ so that `isinstance(obj, SomeABC)` can return True even if the object's class never explicitly inherited from SomeABC, as long as it was registered via `SomeABC.register(OtherClass)` or structurally satisfies the ABC's requirements. This lets unrelated classes (like built-in list) be recognized as implementing collections.abc.Sequence without modifying their actual inheritance chain.
from collections.abc import Sequence

print(isinstance([1,2,3], Sequence))  # True -- list wasn't explicitly declared as Sequence subclass

class MyIterable:
    pass

Sequence.register(MyIterable)
print(isinstance(MyIterable(), Sequence))  # True via virtual registration
Real-world example
A validation framework checks `isinstance(value, collections.abc.Mapping)` to accept both built-in dicts and custom dict-like classes from third-party libraries that were registered as virtual subclasses.
Likely follow-ups
  • What's the performance cost of custom __instancecheck__ implementations?
  • How does register() differ from actual inheritance?
Related topics