Skip to main content
Python Check Datatype Using type() and isinstance()

Python Check Datatype Using type() and isinstance()

This tutorial help to find a variable data type in python, we’ll also learn here how to find the variable datatype and instance type of an object using python.The python has built-in method type() and isinstance() to check datatype for a variable/object.

In Python, each value has a datatype. In Python programming, everything is an object, and data types are classes, with variables being instances (objects) of these classes.

Checkout other python String tutorials:

Python is a language with dynamic typing. So that the Python interpreter only does type checking when code is executed, and that the type of a variable can change over time.

Check DataType Using Python typeof function

We can check a variable type in python using type() method. This method takes a variable as a parameter, and Python returns the class type of the argument passed as a parameter.

Syntax:

type(object)

The object is a required parameter, and it must be a string, integer, list, tuple, set, dictionary, float, or other value.

a = 2
b = 1.2
c = "pythonpip"
d = [1,2,3]
print(type(a))
print(type(b))
print(type(c))
print(type(d))

Output:

<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>

Check Type of Object in Python Using isinstance()

We can check an Object type in python using isinstance() method. This method function also checks if the given object is an instance of the subclass.

Syntax:

isinstance(object, sourceClass)

The Above method checks the object is the instance or subclass of the sourceClass class. it’ll return TRUE if the specified object is of the specified type, otherwise False.

The object is a required two parameters:

object: This is an object to be checked
sourceClass: This is a class, type, or tuple.

a = 2
class Emp:
  name = "Adam"

obj = Emp()

print(isinstance(a, int))
print(isinstance(a, float))
print(isinstance(obj, Emp))

Output:

True
False
True

Leave a Reply

Your email address will not be published. Required fields are marked *