Christian Giacomi

How to perform type checking in Python

Posted — Feb 20, 2022

In Python there are two ways to check the type of a variable or object.

isinstance()

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.

isinstance(object, classinfo)

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

Finally 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

type()

The second way to perform type checking is to use type() which was introduced in version 2.2.

Unfortunately the official documentation recommends using isinstance() due its support for subclasses instead of type()

Furthermore from version 3.6 onwards this way of type checking will not work unless the type has explicitly overridden type.__new__.

“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

If this post was helpful tweet it or share it.