What's the best way to check for type in Python?

Better Stack Team
Updated on February 3, 2023

The built-in type() function is the most commonly used method for checking the type of an object in Python. For example, type(my_variable) will return the type of my_variable. Additionally, you can use the isinstance() function to check if an object is an instance of a particular class or a subclass thereof. For example, isinstance(my_variable, int) will return True if my_variable is an instance of the int class.

Here's an example of using the type() function:

 
x = 5
print(type(x))  # Output: <class 'int'>

y = "hello"
print(type(y))  # Output: <class 'str'>

You can also use isinstance() to check if an object is an instance of a particular class or a subclass thereof. For example,

 
class A:
    pass

class B(A):
    pass

x = A()
y = B()
print(isinstance(x, A))  # Output: True
print(isinstance(y, A))  # Output: True

Here x is an instance of class A and y is an instance of class B, which is a subclass of A, so both would return True when we check if they are instances of A.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →