type() and isinstance() in Python with Examples

What is type() in Python?

Python has a built-in function called type() that helps you find the class type of the variable given as input. For example, if the input is a string, you will get the output as <class ‘str’>, for the list, it will be <class ‘list’>, etc.

Using type() command, you can pass a single argument, and the return value will be the class type of the argument given, example: type(object).

It is also possible to pass three arguments to type(), i.e., type(name, bases, dict), in such case, it will return you a new type object.

Syntax for type()

type() can be used in two ways as shown below:

 type(object)
type(namr, bases, dict)

Parameters: type(object)

  • object: This is a mandatory parameter. If this is only parameter passed to type(), than it will return you the type of the parameter.

Parameters: type(name, bases, dict)

  • name:name of the class.
  • bases: (optional). This is an optional parameter, and it is the base class
  • dict: (optional). This is an optional parameter, and it is a namespace that has the definition of the class.

Return Value

If the object is the only parameter passed to type() then it will return you the type of the object.

If the params passed to type is a type(object, bases, dict), in such case, it will return a new type of object.

Example of type()

In this, example we have a string value, number , float value, a complex number, list, tuple , dict and set. We will use the variables with type to see the output for each of them.

str_list = "Welcome to Guru99"
age = 50
pi = 3.14
c_num = 3j+10
my_list = ["A", "B", "C", "D"]
my_tuple = ("A", "B", "C", "D")
my_dict = {"A":"a", "B":"b", "C":"c", "D":"d"}
my_set = {'A', 'B', 'C', 'D'}

print("The type is : ",type(str_list))
print("The type is : ",type(age))
print("The type is : ",type(pi))
print("The type is : ",type(c_num))
print("The type is : ",type(my_list))
print("The type is : ",type(my_tuple))
print("The type is : ",type(my_dict))
print("The type is : ",type(my_set))

Output:

The type is :<class 'str'>
The type is :<class 'int'>
The type is :<class 'float'>
The type is :<class 'complex'>
The type is :<class 'list'>
The type is :<class 'tuple'>
The type is :<class 'dict'>
The type is :<class 'set'>

Example: Using type() for class object.

When you check the object created from a class using type(), it returns the class type along with the name of the class. In this example, we will create a class and check the object type created from the class test.

class test:
    s = 'testing'

t = test()
print(type(t))

Output:

<class '__main__.test'>

Example: Using the name, bases, and dict in type()

The type can be also called using the syntax: type(name, bases, dict).

The three parameters passed to type()i.e., name, bases and dict are the components that make up a class definition. The name represents the class name, the bases is the base class, and dict is the dictionary of base class attributes.

In this example, we are going to make use of all three params i.e name, bases, and dict in type().

Example:

class MyClass:
  x = 'Hello World'
  y = 50

t1 = type('NewClass', (MyClass,), dict(x='Hello World', y=50))
print(type(t1))
print(vars(t1))

Output:

<class 'type'>
{'x': 'Hello World', 'y': 50, '__module__': '__main__', '__doc__': None}

When you pass all three arguments to type() , it helps you to initialize new class with base class attributes.

What is isinstance() in Python?

Python isinstance is part of python built-in functions. Python isinstance() takes in two arguments, and it returns true if the first argument is an instance of the classinfo given as the second argument.

Syntax isinstance()

isinstance(object, classtype)

Parameters

  • object: An object whose instance you are comparing with classtype. It will return true if the type matches otherwise false.
  • class type: A type or a class or a tuple of types and/or classes.

Return value

It will return true if the object is an instance of classtype and false if not.

Examples of isinstance()

In this section, we will study various examples to learn isinstance()

Example : isinstance() Integer check

The code below compares integer value 51 with type int. It will return true it the type of 51 matches with int otherwise false.

age = isinstance(51,int)
print("age is an integer:", age)

Output:

age is an integer: True

Example : isinstance() Float check

In this example we are going to compare the float value with type float i.e. 3.14 value will be compare with type float.

pi = isinstance(3.14,float)
print("pi is a float:", pi)

Output:

pi is a float: True

Example: isinstance() String check

message = isinstance("Hello World",str)
print("message is a string:", message)

Output:

message is a string: True

Example : isinstance() Tuple check

The code checks for a tuple (1,2,3,4,5) with type tuple. It will return true if the input given is of type tuple and false if not.

my_tuple = isinstance((1,2,3,4,5),tuple)
print("my_tuple is a tuple:", my_tuple)

Output:

my_tuple is a tuple: True

Example : isinstance() Set check

The code checks for a set ({1,2,3,4,5},with type set. It will return true if the input given is of type set and false if not.

my_set = isinstance({1,2,3,4,5},set)
print("my_set is a set:", my_set)

Output:

my_set is a set: True

Example: isinstance() list check

The code checks for a list [1,2,3,4,5],with type list. It will return true if the input given is of type list and false if not.

my_list = isinstance([1,2,3,4,5],list)
print("my_list is a list:", my_list)

Output:

my_list is a list: True

Example: isinstance() dict check

The code checks for a dict({“A”:”a”, “B”:”b”, “C”:”c”, “D”:”d”},with type dict. It will return true if the input given is of type dict and false if not.

my_dict = isinstance({"A":"a", "B":"b", "C":"c", "D":"d"},dict)
print("my_dict is a dict:", my_dict)

Output:

my_dict is a dict: True

Example: isinstance() test on a class

The code shows the type check of class with isinstance() . The object of the class is compared with the name of the class inside isinstance(). It returns true if the object belongs to the class and false otherwise.

class MyClass:
    _message = "Hello World"

_class = MyClass()

print("_class is a instance of MyClass() : ", isinstance(_class,MyClass))

Output:

_class is a instance of MyClass() True

Difference Between type() and isinstance() in Python

type() isinstance()
Python has a built-in function called type() that helps you find the class type of the variable given as input. Python has a built-in function called isinstance() that compares the value with the type given. If the value and type given matches it will return true otherwise false.
The return value is a type object The return value is a Boolean i.e true or false.
class A:
my_listA = [1,2,3]

class B(A):
my_listB = [1,2,3]

print(type(A()) == A)
print(type(B()) == A)

Output:

True
False

In case of type the subclass check gives back false.

class A:
my_listA = [1,2,3]

class B(A):
my_listB = [1,2,3]

print(isinstance(A(), A))
print(isinstance(B(), A))

Output:

True
True

isinstance() gives a truthy value when checked with a subclass.

Summary

  • Python has a built-in function called type() that helps you find the class type of the variable given as input. For example, if the input is a string, you will get the output as <class ‘str’>, for the list, it will be <class ‘list’>, etc.
  • For type(), you can pass a single argument, and the return value will be the class type of the argument given, e.g., type(object).
  • It is also possible to pass three arguments to type(), i.e., type(name, bases, dict), in such case, it will return you a new type object.
  • Python has a built-in function called instance() that compares the value with the type given. It the value and type given matches it will return true otherwise false. Using isinstance(), you can test for string, float, int, list, tuple, dict, set, class, etc.
  • Using isinstance() method, you can test for string, float, int, list, tuple, dict, set, class, etc.