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: pass class Planet(SpaceBody): pass class TerrestrialPlanet(Planet): pass
Look what happens with each of the functions:
>>> earth = TerrestrialPlanet() >>> type(earth) is TerrestrialPlanet True >>> type(earth) is SpaceBody False >>> type(earth) is Planet False >>> isinstance(earth, TerrestrialPlanet) True >>> isinstance(earth, SpaceBody) True >>> isinstance(earth, Planet) True
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().