isinstance(obj, cls) returns True if obj's type is cls or any subclass of cls, which is why it's the recommended way to check types in Python instead of comparing type(obj) directly, since that comparison rejects subclasses. Passing a tuple as the second argument checks against multiple types at once, matching if obj is an instance of any of them.
1Understanding isinstance()
isinstance(obj, cls) returns True if obj's type is cls or any subclass of cls, which is why it's the recommended way to check types in Python instead of comparing type(obj) directly, since that comparison rejects subclasses. Passing a tuple as the second argument checks against multiple types at once, matching if obj is an instance of any of them.
Remember bool is technically a subclass of int in Python, so a boolean value also counts as an instance of int, which occasionally causes surprising bugs when checking for 'any number'.
print(isinstance(5, int))
print(isinstance("hi", (int, str)))
print(isinstance(5, str))2Practical Example
Here is a real-world application of isinstance() showing how it is used in production Python code.
def describe(value):
if isinstance(value, bool):
return "boolean"
if isinstance(value, (int, float)):
return "number"
return "other"
print(describe(True))
print(describe(3.14))3Best Practices
Follow these guidelines when working with isinstance():
1. Use isinstance() rather than direct type comparisons so subclasses are correctly recognized
2. Pass a tuple of types to check for several acceptable types in one call, instead of chaining multiple checks with or
3. Guard against bool being a subclass of int explicitly if that distinction matters for your logic
Tip: Remember bool is technically a subclass of int in Python, so a boolean value also counts as an instance of int, which occasionally causes surprising bugs when checking for 'any number'.
print(isinstance(5, int))
print(isinstance("hi", (int, str)))
print(isinstance(5, str))