How to Use isinstance Function in Python: Simple Guide
Use the
isinstance(object, classinfo) function in Python 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 an object's type before using it.Syntax
The isinstance function takes two arguments: the object you want to check, and the class or tuple of classes you want to check against.
- object: The variable or value to test.
- classinfo: A class, type, or a tuple of classes/types.
It returns True if the object is an instance of the classinfo or any subclass, 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 consider inheritance. - Passing a single class inside a tuple by mistake, like
(int)instead of(int,). - Checking against mutable types incorrectly.
Always use isinstance for type checks to support inheritance and multiple types.
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 element (missing comma) print(isinstance(d, (Dog))) # False # Correct tuple with one element print(isinstance(d, (Dog,))) # True
Output
False
True
False
True
Quick Reference
Remember these tips when using isinstance:
- Use it to check if an object matches a type or any subclass.
- Pass a tuple to check multiple types at once.
- It returns
TrueorFalse. - Supports inheritance, unlike
type().
Key Takeaways
Use isinstance(object, classinfo) to check an object's type safely.
It returns True if the object is an instance of the class or any subclass.
Pass a tuple of classes to check multiple types at once.
Avoid using type() for type checks when inheritance matters.
Remember to use a comma for single-element tuples in classinfo.