To check the data type of a variable in Python, use either the type() or isinstance() method.
Data type checking is essential for debugging, validation, optimization, and type-safe readability.
Method 1: Using type()
The type() method returns the type as a class object.
It is helpful when you need the precise type name of a variable.
For example, type(“Chat”) will return “str” because it is a string literal.
str = 'AppDividend' print(type(str)) # Output: <class 'str'> int = 123 print(type(int)) # Output: <class 'int'> float = 21.19 print(type(float)) # Output: <class 'float'> negative = -19 print(type(negative)) # Output: <class 'int'> dictionary = {'blog': 'AppDividend'} print(type(dictionary)) # Output: <class 'dict'> list = [1, 2, 3] print(type(list)) # Output: <class 'list'> tuple = (19, 21, 46) print(type(tuple)) # Output: <class 'tuple'> set = {19, 21, 46} print(type(set)) # Output: <class 'set'>
The above program demonstrates that we compared the types directly and printed the results.
Checking against a specific type
With the help of the if condition and the is operator, we can use the type() function to check any variable’s type against any specific type for exact type matches.
var = "V2" if type(var) is str: print(f"{var} is a string")
In this code, we are confirming whether our input variable is a string or not. Since it is a string, if condition returns True and the statement is printed.
Inheritance does not work
The type() function does not account for inheritance, which is a significant disadvantage of this approach.
class Auto: pass class Car(Auto): pass tata = Car() print(type(tata) is Auto) # Output: False
In this code, object “tata” is inherited from the Car class, and hence it is an inherited object.
The type() function does not consider “tata” an Auto object in this case because it does not count inheritance, which is why it returns False.
When it comes to inheritance, this approach is not suitable. I recommend using the isinstance() function for that.
NoneType
None is a singleton of NoneType.
ntype = None print(type(ntype)) # Output: <class 'NoneType'>
Method 2: Using isinstance()
The isinstance() method checks against a class, a tuple of classes, or abstract base classes (ABCs from collections.abc) and returns True or False based on the input.
# isinstance(value, type_or_tuple_of_types) num = 10 print(isinstance(num, int)) # Output: True print(isinstance(num, str)) # Output: False main_list = [10, 20, 30] print(isinstance(main_list, list)) # Output: True main_dict = {"a": 1, "b": 3} print(isinstance(main_dict, dict)) # Output: True
Using with Multiple Types
You can also check against multiple types at once.
num = 2.72 print(isinstance(num, (int, float))) # Output: True
Inheritance handling
It can handle inheritance very well and returns the proper output.
class Auto: pass class Car(Auto): pass tata = Car() print(isinstance(tata, Auto)) # Output: True (inherits from Auto)
That’s all!