Python isinstance() function is used to check if an object is an instance of the specified class or not.
Python isinstance()
Python isinstance() function syntax is:
1 2 3 |
isinstance(object, classinfo) |
This function returns True
if the object is instance of classinfo argument or instance of classinfo subclass.
If the object is not an instance of classinfo or its subclass, then the function returns False
.
classinfo argument can be a tuple of types. In that case, isinstance() will return True if the object is an instance of any of the types.
If classinfo is not a type or tuple of types, a TypeError
exception is raised.
Python isinstance() example
Let’s look at some simple examples of isinstance() function with built-in data types, such as string, tuple, list, dict, bytes etc.
Python isinstance() number
1 2 3 4 5 6 |
i = 10 print('i is int:', isinstance(i, int)) f = 10.5 print('f is float:', isinstance(f, float)) |
Output:
1 2 3 4 |
i is int: True f is float: True |
Python isinstance() string
1 2 3 4 |
s="a" print('s is str:', isinstance(s, str)) |
Output:
1 2 3 |
s is str: True |
Python isinstance() bytes
1 2 3 4 |
b = bytes('abc', 'utf-8') print('b is bytes:', isinstance(b, bytes)) |
Output:
1 2 3 |
b is bytes: True |
Python isinstance() tuple
1 2 3 4 |
t = (1, 2) print('t is tuple:', isinstance(t, tuple)) |
Output:
1 2 3 |
t is tuple: True |
Python isinstance() list
1 2 3 4 |
li = [] print('li is list:', isinstance(li, list)) |
Output:
1 2 3 |
li is list: True |
Python isinstance() dict
1 2 3 4 |
d = {} print('d is dict:', isinstance(d, dict)) |
Output:
1 2 3 |
d is dict: True |
Python isinstance() class and inheritance
Let’s look at an example of isinstance() function with custom class and inheritance with multiple classes.
1 2 3 4 5 6 7 8 9 10 11 12 |
class Person: name="" class Employee(Person): id = 0 p = Person() e = Employee() print('p isinstance of Person:', isinstance(p, Person)) print('p isinstance of Employee:', isinstance(p, Employee)) print('e isinstance of Person:', isinstance(e, Person)) print('e isinstance of Employee:', isinstance(e, Employee)) |
Output:
1 2 3 4 5 6 |
p isinstance of Person: True p isinstance of Employee: False e isinstance of Person: True e isinstance of Employee: True |
Python isinstance() tuple of classes
1 2 3 4 |
print('p is an instance of Person or Employee:', isinstance(p, (Person, Employee))) print('e is an instance of Person or Employee:', isinstance(e, (Person, Employee))) |
Output:
1 2 3 4 |
p is an instance of Person or Employee: True e is an instance of Person or Employee: True |
Summary
Python isinstance() is a utility function to check if an object is of a specific type or not. We can use it to perform a type check and perform operations based on the type of object.
Reference: Official Documentation