Open In App

type and isinstance in Python

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.




# 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.




# 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.




# 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.




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.




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.




# 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




# 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




# 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

Article Tags :