Use isinstance() to check if an object is of a specific type or a subclass of it.
Example: Check if an object is of type str

mystr = "hello"
if isinstance(mystr, str):
   print("mystr is a string")

This will return true even if mystr is an instance of a subclass of str.
To check for an exact type (not allowing subclasses), use type():

if type(mystr) is str:
   print("mystr is exactly a string")

Use isinstance() in most cases, especially when you want to allow subclasses. It is more flexible and considered more Pythonic.

Need Help With Python Development?

Work with our skilled Python developers to accelerate your project and boost its performance.

Hire Python Developers

Support On Demand!

Related Q&A