Skip to content
Related Articles

Related Articles

type and isinstance in Python

View Discussion
Improve Article
Save Article
  • Difficulty Level : Expert
  • Last Updated : 25 Jul, 2022
View Discussion
Improve Article
Save Article

In this article, we will cover about type() and isinstance() function in Python, and what are the differences between type() and isinstance().

What is type in Python?

Python has a built-in method called type which generally comes in handy while figuring out the type of the variable used in the program in the runtime. The canonical way to check for type in Python is given below:

Syntax of type() function

type(object)
type(name, bases, dict)

Example 1: Example of type() with a Single Object Parameter

In this example, we are trying to check the data type of each variable, such as x, s, and y using type() function.

Python3




# Python code type() with a single object parameter
x = 5
s = "geeksforgeeks"
y = [1, 2, 3]
print(type(x))
print(type(s))
print(type(y))

Output:

class 'int'
class 'str'
class 'list'

Example 2: Example of type() with a name, bases, and dict Parameter 

If you need to check the type of an object, it is recommended to use the Python isinstance() function instead. It’s because isinstance() function also checks if the given object is an instance of the subclass.

Python3




# Python code for type() with a name,
# bases and dict parameter
 
o1 = type('X', (object,), dict(a='Foo', b=12))
 
print(type(o1))
print(vars(o1))
 
 
class test:
    a = 'Foo'
 
 
b = 12
 
o2 = type('Y', (test,), dict(a='Foo', b=12))
print(type(o2))
print(vars(o2))

Output:

{'b': 12, 'a': 'Foo', '__dict__': , '__doc__': None, '__weakref__': }
{'b': 12, 'a': 'Foo', '__doc__': None}

What is isinstance() in Python?

The isinstance() function checks if the object (first argument) is an instance or subclass of the class info class (second argument).

Syntax of isinstance() function

Syntax: isinstance(object, classinfo) 

Parameter:

  • object : object to be checked
  • classinfo : class, type, or tuple of classes and types

Return: true if the object is an instance or subclass of a class, or any element of the tuple false otherwise. 

If class info is not a type or tuple of types, a TypeError exception is raised.

Example 1: 

In this example, we will see test isinstance() for the class object.

Python3




# Python code for  isinstance()
class Test:
    a = 5
 
 
TestInstance = Test()
 
print(isinstance(TestInstance, Test))
print(isinstance(TestInstance, (list, tuple)))
print(isinstance(TestInstance, (list, tuple, Test)))

Output:

True
False
True

Example 2:

In this example, we will see test isinstance() for the integer, float, and string object.

Python3




weight = isinstance(17.9, float)
print("is a float:", weight)
 
num = isinstance(71, int)
print("is an integer:", num)
 
 
string = isinstance("Geeksforgeeks", str)
print("is a string:", string)

Output:

is a float: True
is an integer: True
is a string: True

Example 3:

In this example, we will see test isinstance() for the tuple, list, dictionary, and set object.

Python3




tuple1 = isinstance(('A', 'B', 'C'),tuple)
print("is a tuple:", tuple1)
 
set1 = isinstance({'A', 'B', 'C'},set)
print("is a set:", set1)
 
list1 = isinstance(['A', 'B', 'C'],list)
print("is a list:", list1)
 
dict1 = isinstance({"A":"1", "B":"2", "C":"3"},dict)
print("is a dict:", dict1)

Output:

is a tuple: True
is a set: True
is a list: True
is a dict: True

What are the differences between type() and isinstance()?

One elementary error people make is using the type() function where isinstance() would be more appropriate.

  • If you’re checking to see if an object has a certain type, you want isinstance() as it checks to see if the object passed in the first argument is of the type of any of the type objects passed in the second argument. Thus, it works as expected with subclassing and old-style classes, all of which have the legacy type object instance.
  • type(), on the other hand, simply returns the type object of an object, and comparing what it returns to another type object will only yield True when you use the exact same type object on both sides. In Python, it’s preferable to use Duck Typing( type checking is deferred to run-time, and is implemented by means of dynamic typing or reflection) rather than inspecting the type of an object. 

Python3




# Python code to illustrate duck typing
 
 
class User(object):
    def __init__(self, firstname):
        self.firstname = firstname
 
    @property
    def name(self):
        return self.firstname
 
 
class Animal(object):
    pass
 
 
class Fox(Animal):
    name = "Fox"
 
 
class Bear(Animal):
    name = "Bear"
 
 
# Use the .name attribute (or property) regardless of the type
for a in [User("Geeksforgeeks"), Fox(), Bear()]:
    print(a.name)

Output:

Geeksforgeeks
Fox
Bear
  • The next reason not to use type() is the lack of support for inheritance.

Python3




# python code to illustrate the lack of
# support for inheritance in type()
 
 
class MyDict(dict):
    """A normal dict, that is always created with an "initial" key"""
 
    def __init__(self):
        self["initial"] = "some data"
 
 
d = MyDict()
print(type(d) == dict)
print(type(d) == MyDict)
 
d = dict()
print(type(d) == dict)
print(type(d) == MyDict)

Output:

False
True
True
False
  • The MyDict class has all the properties of a dict, without any new methods. It will behave exactly like a dictionary. But type() will not return the expected result. Using isinstance() is preferable in this case because it will give the expected result: 

Python3




# python code to show isinstance() support
# inheritance
class MyDict(dict):
    """A normal dict, that is always created with an "initial" key"""
 
    def __init__(self):
        self["initial"] = "some data"
 
 
d = MyDict()
print(isinstance(d, MyDict))
print(isinstance(d, dict))
 
d = dict()
print(isinstance(d, MyDict))
print(isinstance(d, dict))

Output:

True
True
False
True

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!