Q&A library Python

How do I check the type of a variable in Python?

Python Beginner checkingisinstancetype

Short answer

Use isinstance, which respects inheritance and accepts a tuple of types, rather than comparing type() directly. Be aware that bool is a subclass of int, so a True value passes an int check.

The short version

Use isinstance(value, int) to check a variable's type. It is preferred over type(value) == int because it respects inheritance and accepts a tuple of types to check several at once. One surprise to remember: bool is a subclass of int, so isinstance(True, int) is True.

The basic check

isinstance(5, int)        # True
isinstance(5.0, float)    # True
isinstance("x", str)      # True

isinstance returns a plain boolean, so it drops straight into an if.

Checking several types at once

Pass a tuple to accept any of several types, which is cleaner than chaining or.

isinstance(5, (int, float))    # True, it is one of these

This is the idiomatic way to write "is this a number", accepting both int and float.

Why isinstance over type

Comparing type(x) == SomeClass checks for that exact type and ignores subclasses. isinstance returns True for subclasses too, which is usually what you want, because a subclass is a kind of its parent.

class Animal: pass
class Dog(Animal): pass

d = Dog()
type(d) == Animal        # False, exact type only
isinstance(d, Animal)    # True, a Dog is an Animal

Use type(x) is SomeClass only in the rare case where you genuinely need the exact type and want to exclude subclasses.

The bool surprise

Because bool is a subclass of int in Python, a boolean passes an integer check.

isinstance(True, int)    # True

This is technically correct but catches people out. If you need to exclude booleans from a numeric check, test for bool first and reject it, or use type(x) is int.

Checking for None

Do not use isinstance to check for None. There is only one None, so identity is the right test.

if value is None:
    ...

Avoiding type checks entirely

Often the more Pythonic approach is not to check the type at all, but to try the operation and handle failure, which is called duck typing. Reach for isinstance when you genuinely need to branch on type, for example when a function accepts either a single item or a list, and let ordinary code handle the common cases without a type check.

Need this solved on your own data?

The library is free and always will be. When the problem is bigger than an answer, we take on the work.

Start a project