Advertisement
Intermediate Python, Metaclasses & Class Customization

What is the practical difference between isinstance(obj, cls) and type(obj) is cls, particularly regarding metaclasses and inheritance?

Short answer

isinstance() respects the full inheritance hierarchy (and can be customized via __instancecheck__ on a metaclass, as ABCs do for virtual subclassing), returning True for subclass instances too.

Save Python mock interview
Advertisement
AModel answer
isinstance() respects the full inheritance hierarchy (and can be customized via __instancecheck__ on a metaclass, as ABCs do for virtual subclassing), returning True for subclass instances too. `type(obj) is cls` only matches the exact type, ignoring subclasses entirely -- so it's stricter and generally discouraged unless you specifically need to exclude subclass instances.
class Animal: pass
class Dog(Animal): pass

d = Dog()
print(isinstance(d, Animal))   # True -- respects inheritance
print(type(d) is Animal)       # False -- exact type only
Real-world example
A serialization framework uses isinstance() checks against ABCs (like collections.abc.Mapping) so it correctly handles any dict-like object, including custom subclasses, rather than only exact dict instances.
Likely follow-ups
  • How does __instancecheck__ let ABCs support virtual subclasses?
  • When is the exact-type check actually the right choice?
Related topics