What's the canonical way to check for type in python?


If you want to check if an object, x is an instance of exactly a given type(not a subtype), you can use typeto get its type and check using is statement.

example

x = "Hello"
if type(x) is str:
   print("x is an instance of str")

Output

This will give the output

x is an instance of str

If you want to check if x is an instance of a MyClass or any subclass of MyClass, you can use the isinstance method call. 

example

x = "Hello"
if isinstance(x, str):
   print("x is an instance of str")

Output

This will give the output

x is an instance of str

Updated on: 05-Mar-2020

87 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements