Python: Checking Type of Variable

isinstance() seems to be the preferred way to check the type of a Python variable. It checks if the variable (object) is an instance of the class object being checked against.

# Variables of different types
i = 1
f = 0.1
s = "Hell"
l = [0, 1, 2]
d = {0:"Zero", 1:"One"}
t = (0, 1, 2)
b = True
n = None

All of the following return True:

isinstance(i, int)
isinstance(f, float)
isinstance(s, str)
isinstance(l, list)
isinstance(d, dict)
isinstance(t, tuple)

True and False are an instance of bool, so:

isinstance(b, bool)

What about None? For that, there is always:

n is None

3 thoughts on “Python: Checking Type of Variable

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.