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

Better Stack Team
Updated on November 23, 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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github