How to Use isinstance in Python: Simple Guide with Examples
Use
isinstance(object, classinfo) to check if an object is an instance of a class or a tuple of classes. It returns True if the object matches the type, otherwise False. This helps you safely test types before running code that depends on them.Syntax
The isinstance function takes two arguments:
- object: The variable or value you want to check.
- classinfo: A class, type, or a tuple of classes/types to check against.
It returns True if the object is an instance of the classinfo or any class in the tuple, otherwise False.
python
isinstance(object, classinfo)Example
This example shows how to check if a variable is an integer or a string using isinstance. It prints messages based on the type.
python
x = 10 if isinstance(x, int): print("x is an integer") name = "Alice" if isinstance(name, str): print("name is a string") # Check multiple types value = 3.14 if isinstance(value, (int, float)): print("value is a number")
Output
x is an integer
name is a string
value is a number
Common Pitfalls
Some common mistakes when using isinstance include:
- Using
type()instead ofisinstance()which does not support inheritance checks. - Passing a single class inside a tuple incorrectly (missing comma).
- Confusing
isinstancewithissubclasswhich checks class relationships, not instances.
python
class Animal: pass class Dog(Animal): pass d = Dog() # Wrong: type() does not consider inheritance print(type(d) == Animal) # False # Right: isinstance() considers inheritance print(isinstance(d, Animal)) # True # Wrong: tuple with one class missing comma print(isinstance(d, (Animal))) # False # Right: tuple with one class print(isinstance(d, (Animal,))) # True
Output
False
True
False
True
Quick Reference
| Usage | Description |
|---|---|
| isinstance(obj, Class) | Check if obj is instance of Class or subclass |
| isinstance(obj, (Class1, Class2)) | Check if obj is instance of any class in tuple |
| Returns True or False | Boolean result of the type check |
Key Takeaways
Use isinstance(obj, Class) to check an object's type safely including inheritance.
Pass a tuple of classes to check multiple types at once.
Avoid using type() for type checks when inheritance matters.
Remember to include a comma for single-class tuples in isinstance.
isinstance returns True or False, useful for conditional code based on type.