Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

Python - Checking Type of Variable

📅 2010-Jan-28 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ python, types ⬩ 📚 Archive

isinstance seems to be the preferred method 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

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧