5.10 Type Checking
type() vs isinstance() for checking an object's type, why isinstance() is preferred for validation because it handles subclassing, and what id() is used for.
type()
Returns an object’s exact type. Good for debugging/inspection, but generally NOT recommended for validation logic (see isinstance() below), since it does an exact match and ignores subclassing.
>>> type(5) == int
True
isinstance()
What Is It?
Checks whether an object IS an instance of a type, INCLUDING subclasses.
Why Is It Preferred?
It’s preferred over type() for validation because it correctly handles inheritance — e.g. bool is a subclass of int, so isinstance(True, int) is True even though type(True) == int is False.
>>> isinstance(5, int)
True
>>> isinstance(True, int) # bool IS-A int (subclass)
True
>>> type(True) == int # exact type match fails here
False
id()
Returns an object’s unique identity (see 5.2 Python Object Model) — used far more often for understanding reference/aliasing behavior than for everyday type checking.
>>> id(5)
11755816
Quick Interview Answer
“
type()returns an object’s exact type and does an exact match, which breaks for subclasses.isinstance()checks whether an object IS an instance of a type INCLUDING subclasses, which is why it’s the preferred choice for validation —isinstance(True, int)isTruesinceboolsubclassesint, even thoughtype(True) == intisFalse.id()is a different tool entirely — it returns identity, used for understanding references, not for type checks.”
Common Mistakes
- Using
type(x) == SomeClassfor validation when a subclass instance should also pass —isinstance()handles that correctly,type()does not. - Forgetting that
boolis a subclass ofint, so anisinstance(x, int)check unexpectedly also acceptsTrue/False. - Reaching for
id()when a simple==orisinstance()check was actually what was needed.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form