Python isinstance() Function

Description

The isinstance() function is used to check if an object is of a known type, similar to type().

Differences between isinstance() and type():

  • type() does not consider subclasses as a type of the parent class and does not take inheritance into account.

  • isinstance() considers subclasses as a type of the parent class and takes inheritance into account.

If you want to check if two types are the same, it is recommended to use isinstance().

Syntax

The syntax of the isinstance() method is as follows:

isinstance(object, classinfo)

Parameters

  • object — The instance object.
  • classinfo — This can be a direct or indirect class name, a basic type, or a tuple composed of them.

Return Value

If the type of the object is the same as the type of the second parameter (classinfo), it returns True; otherwise, it returns False.

Examples

The following shows examples of using the isinstance function:

1.

>>> a = 2
>>> isinstance(a, int)  # True
>>> isinstance(a, str)  # False
>>> isinstance(a, (str, int, list))  # True

2.

a = 5
b = [10, 20, 37]
print(isinstance(a, int))  # True
print(isinstance(b, list))  # True
print(isinstance(b, (int, list, str)))  # True

Python isinstance() Function

  • isinstance(a, int) returns True because a is an integer.
  • isinstance(b, list) returns True because b is a list.
  • isinstance(b, (int, list, str)) returns True because b is a list, which is one of the types in the tuple.

Differences between type() and isinstance():

class A:
    pass
class B(A):
    pass
isinstance(A(), A)  # returns True
type(A()) == A  # returns True
isinstance(B(), A)  # returns True
type(B()) == A  # returns False

isinstance()

type()

Syntax: isinstance(object, class) Syntax: type(object)

It checks if an object is of a specific class type

It returns the class type of an object

It can check if the object belongs to a class and its subclasses

It cannot deal with inheritance

It is faster as compared to type() It is slower than isinstance()
It returns either True or False It returns the type of the object
It can check for multiple classes at a time It cannot do this
Example: isinstance(10, (int, str)) Example: type(10)
https://www.runoob.com/python/python-func-isinstance.html
https://www.geeksforgeeks.org/python/python-isinstance-method/

Leave a Comment