2 min read

type() vs isinstance() in Python

Learn the difference between type and isinstance and when to choose which function.
type() vs isinstance() in Python
2 ways to do type checking in Python

Sections Covered

  1. Importance of type checking in Python
  2. type vs isinstance
  3. Difference between isinstance and type
  4. Why should you choose isinstance over type?

Importance of type checking in Python

Python is a dynamically typed language. A variable can be assigned multiple values during the code lifetime.

x = "Pylenin" #string
x = 1992 #integer
x = [1, 2, 3] #list

So it is necessary to keep track of the data type that your variable is holding at a certain stage of the code.

That’s where built-in functions like type() and isinstance() come into play.

type vs isinstance

Code - Using type()

x = "Pylenin"

# Check type of x
print(type(x))

# Perform boolean comparison
# Using is operator
print(type(x) is str)

Output

<class 'str'>
True
True

The isinstance() function allows you to perform the above boolean comparison.

Code - Using isinstance()

x = "Pylenin"

# Using isinstance
print(isinstance(x, str))

Output

True

Difference between isinstance and type

1st Difference - Speed

The isinstance() function is faster than the type function. We can compare both their performance by using the timeit library.

>>> python -m timeit -s "x = 'Pylenin'" "type(x) is str"
5000000 loops, best of 5: 60.4 nsec per loop

>>> python -m timeit -s "x = 'Pylenin'" "isinstance(x, str)"
5000000 loops, best of 5: 42.7 nsec per loop

As you can see, the isinstance() function is 30 times faster than type() function.

2nd Difference - isinstance can check for subclass, type cannot

The isinstance() method can check if an object belongs to either a class or a subclass. type cannot check this.

Code

class Person:
    def __init__(self):
       self.type = "human"

class Pylenin(Person):
    
    name = "Pylenin"

myself = Pylenin()

print(type(myself) is Pylenin)
print(isinstance(myself, Pylenin))

Output

True
True

Since myself is an object of Pylenin class, both type() and isinstance() return True.

However, Pylenin inherits from Person class. It’s the subclass of Person class.

So ideally, myself should also belong to Person class.

Code

class Person:
    def __init__(self):
       self.type = "human"

class Pylenin(Person):

    name = "Pylenin"

myself = Pylenin()

print(type(myself) is Person)
print(isinstance(myself, Person))

Output

False # type() returned False
True

As you can see, the type() function is unable to link myself object to the Person class.

So type() doesn’t work with inheritance.

Why should you choose isinstance over type?

There are 2 reasons to choose isinstance() function over type().

  1. isinstance() is faster than type().
  2. isinstance() can deal with inheritance and type() cannot.

Learn more about the applications of isinstance() function in Python.