type and isinstance in Python
Last Updated :
25 Jul, 2022
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
Similar Reads
Inheritance in Python | Set 2
Prerequisite : basics of inheritance in Python, Inheritance, examples of object, issubclass and super There are 2 built-in functions in Python that are related to inheritance. They are: 1. isinstance(): It checks the type of an object. Its syntax is: isinstance(object_name, class_name) It would retu
4 min read
Types of inheritance Python
Inheritance is defined as the mechanism of inheriting the properties of the base class to the child class. Here we a going to see the types of inheritance in Python. Types of Inheritance in Python Types of Inheritance depend upon the number of child and parent classes involved. There are four types
3 min read
JS Equivalent to Python isinstance()
In Python, the isinstance() function is used to check if an object is an instance of a specific class or a subclass thereof. Itâs an essential part of object-oriented programming in Python and helps ensure that the object is of the desired type before performing certain operations. In this article,
3 min read
type() function in Python
The type() function is mostly used for debugging purposes. Two different types of arguments can be passed to type() function, single and three arguments. If a single argument type(obj) is passed, it returns the type of the given object. If three argument types (object, bases, dict) are passed, it re
5 min read
Type Hints in Python
Type hints are a feature in Python that allow developers to annotate their code with expected types for variables and function arguments. This helps to improve code readability and provides an opportunity to catch errors before runtime using type checkers like mypy.Using Type Hints in Python1. Varia
3 min read
Inheritance in Python
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (called a child or derived class) to inherit attributes and methods from another class (called a parent or base class). This promotes code reuse, modularity, and a hierarchical class structure. In this arti
7 min read
Type Conversion in Python
Python defines type conversion functions to directly convert one data type to another which is useful in day-to-day and competitive programming. This article is aimed at providing information about certain conversion functions. There are two types of Type Conversion in Python: Python Implicit Type C
5 min read
Inheritance and Composition in Python
Prerequisite - Classes and Objects in Python This article will compare and highlight the features of is-a relation and has-a relation in Python. What is Inheritance (Is-A Relation)? It is a concept of Object-Oriented Programming. Inheritance is a mechanism that allows us to inherit all the propertie
4 min read
Instance method in Python
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to
2 min read
Creating Instance Objects in Python
In Python, an instance object is an individual object created from a class, which serves as a blueprint defining the attributes (data) and methods (functions) for the object. When we create an object from a class, it is referred to as an instance. Each instance has its own unique data but shares the
3 min read