← back to blogposts

Should I use type() or isinstance() ?


Both should help you achieve the same result, checking for a given object's type. But they are not quite the same.

TL;DR: type() checks just for the object's type (classname), while isinstance() is True for direct, indirect, or virtual subclasses, too.

That said, imagine you have a structure like this:

class SpaceBody:

class Planet(SpaceBody):

class TerrestrialPlanet(Planet):

Look what happens with each of the functions:

>>> earth = TerrestrialPlanet()

>>> type(earth) is TerrestrialPlanet
>>> type(earth) is SpaceBody
>>> type(earth) is Planet

>>> isinstance(earth, TerrestrialPlanet)
>>> isinstance(earth, SpaceBody)
>>> isinstance(earth, Planet)

Note: always use is instead of == while checking identity and not value, they were both designed for something else and could cause unexpected behaviour when used interchangeably.

Now, what we usually want, is the isinstance() approach, as Earth should always be a planet, right? But if you need to check for a specific type or class, use type(). There is no right or wrong, think about what you need to accomplish in your situation. And have in mind that isinstance() is also a bit faster than type().

Add a comment
You can include your email if you want a response from the author.