The main difference between type()
and isinstance()
is that type(object)
returns the type of an object and isinstance(object, class
) returns True
if the object
argument is an instance of the class
argument or in a direct or indirect subclass relationship.
To strengthen your understanding, let’s quickly recap the syntactical definitions of both functions:
type(object)
β Returns a string representation of the objectβs type.isinstance(object, class)
β Returns a BooleanTrue
if the object is an instance of the class, andFalse
otherwise.
The following examples of both functions show the difference when checking whether an object is of the type list:
>>> type([1, 2, 3]) <class 'list'> >>> isinstance([1, 2, 3], list) True
Youβd use type()
to check for the exact type of an object. Youβd use isinstance()
to confirm your suspicions regarding the type of an object. The function isinstance()
is more robust in that you donβt rely on tiny string differences, and it also works with type inheritance. For example, if A inherits from B which inherits from C, an object of type C is also an instance of A.
In particular, here’s a list of differences between type()
and isinstance()
:
- Return value:
type()
returns a string whereasisinstance()
returns a Boolean. - Arguments:
type()
takes one argument whereasisinstance()
takes two arguments. - Purpose:
type()
is commonly used if you don’t know the type of an object whereasisinstance()
is commonly used to confirm your suspicion regarding a type of an object. - Flexibility:
type()
can be used with one argument or with three arguments to create a new instance of a certain type, whereasisinstance()
must be used with two arguments. - Multi-Check:
type()
can check only one object whereasisinstance()
can check multiple classes for a given instance if you use a tuple of values as a second argument. - Inheritance:
type()
doesn’t return any information of the subclass relationship whereasisinstance()
works on direct and indirect subclass relations as well.
On the other hand, here’s a list of similarities between type()
and isinstance()
:
- Purpose:
type()
andisinstance()
are both used to learn more about the type of a given object. - Origin:
type()
andisinstance()
are both Python built-in functions that can be used without importing any library. - Space:
type()
andisinstance()
both concern object-oriented programming.
To learn more about object-oriented programming and become a master, check out our Finxter Computer Science Academy course:
You can watch my introductory video on the type()
function here:
And feel free to also watch my introductory video about the isinstance()
function here: