In Python there are two ways to check the type of a variable or object.
This is an in built function which takes two parameters and is the preferred way to check the type of a variable or object. This function also takes into account subclasses.
The documentation explicitly states the following:
“Return True if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof.”
This makes it extremely flexible when performing type checking.
So for example if you wanted to check if a variable is a string you could do the following.
name = "Marvin" res = isinstance(name, str) print(res) # will return True
The same goes for any other type in Python, so checking for int would look like so.
meaning_of_life = 42 res = isinstance(meaning_of_life, int) print(res) # will return True
You can also use the function to test against custom types.
class Android: name = "Marvin" marvin = Android() res = isinstance(marvin, Android) print(res) # will return True
isinstance() also accepts a tuple as
classinfo and allows you to test multiple types at the same time.
name = "Marvin" res = isinstance(name, (float, int, list, dict, tuple)) print(res) # will return False since name is of type str
The second way to perform type checking is to use
type() which was introduced in version
Unfortunately the official documentation recommends using
isinstance() due its support for subclasses instead of
Furthermore from version
3.6 onwards this way of type checking will not work unless the type has explicitly overridden
“Changed in version 3.6: Subclasses of type which don’t override type.new may no longer use the one-argument form to get the type of an object.”
As can be seen here