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

PythonProgramming

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
raja
Published on 18-Apr-2018 14:27:22
Advertisements