Type and isinstance in Python

PythonServer Side ProgrammingProgramming

In this article, we will learn about isinstance() and type() function available in Python 3.x. Or earlier. These methods basically are used to check references and nature of the entities.

Isinstance() Method

Syntax

isinstance(object_entity, comparison_equivalent)

Return Value − True if object_entity matches with the comparison_equivalent

Now let us see how the isinstance() method works?

Example

class Test:
   var = 786
   TestInstance = Test()
print(isinstance(TestInstance, Test))
print(isinstance(TestInstance, (list, tuple)))
print(isinstance(TestInstance, (list, tuple, Test)))

Output

True
False
True

The first & third line displayed true because the reference of Test & TestInstance matched. Whereas the second line displays False as the reference of TestInstance doesn’t match with list & tuple references.

Let us look at another example to gain a better understanding.

Example

 Live Demo

Test= [1, 2, 3]
result = isinstance(Test, list)
print(Test,'list:', result)
result = isinstance(Test, dict)
print(Test,'dict:', result)
result = isinstance(Test, (dict, list))
print(Test,'dict or list:', result)

Output

[1, 2, 3] list: True
[1, 2, 3] dict: False
[1, 2, 3] dict or list: True

Here whenever the Test matches with the list instance True is displayed on the screen, False otherwise.

Type() Method

Syntax

type(entity)

Return Value − The type of the entity passed as an argument

Now let us see how the type() method works?

Example

 Live Demo

Dictinp = {1:'Tutorial', 2:'Point'}
print(type(Dictinp))
Listinp = ['t','u','t']
print(type(Listinp))
Tupleinp = ('Tut', 'orial', 'Point')
print(type(Tupleinp))

Output

<class 'dict'>
<class 'list'>
<class 'tuple'>

Here the output contains a respected type of the entity passed during the method call. This type can also be used in comparison and other conditional statements.

Now let us look an example on conditional statements

Example

 Live Demo

Listinp = ['t','u','t']
Tupleinp = ('Tut', 'orial', 'Point')
if type(Listinp) is not type(Tupleinp):
   print("Type mismatch")
else:
   print("TYpe match")

Output

Type Mismatch

Here Type mismatch is displayed as list and tuple are two different data types.

Conclusion

In this article, we learnt the implementation of type() & isinstance() method in Python 3.x. Or earlier.

raja
Published on 29-Aug-2019 10:18:38
Advertisements