To check the data type of a variable in Python, you can use the “type()” method. For example, type(“ChatGPT”) will return “str” because it is a string data type.
The type() is a built-in method that returns the class type of the argument(object) passed as a parameter. You place the variable inside a type() function, and Python returns the data type.
Syntax
type(object)
Parameters
The object argument is required; it can be a string, integer, list, tuple, set, dictionary, float, etc.
Example
str = 'AppDividend'
print(type(str))
int = 123
print(type(int))
float = 21.19
print(type(float))
negative = -19
print(type(negative))
dictionary = {'blog':'AppDividend'}
print(type(dictionary))
list = [1, 2, 3]
print(type(list))
tuple = (19, 21, 46)
print(type(tuple))
Output
Don’t use __class__ to check the data type in Python.
In Python, names that start with underscores are semantically not a part of the public API, and it’s a best practice for users to avoid using them. (Except when it’s compulsory.)
Since type gives us an object class, we should avoid getting __class__ directly.
class Foo(object):
def foo(self):
print(self.__class__)
f = Foo()
f.foo()
Output
Let’s use type() function syntax, which is much better than this.
class Foo(object):
def foo(self):
print(type(self))
f = Foo()
f.foo()
Output
<class '__main__.Foo'>
Don’t use __class__, a semantically nonpublic API, to get the variable type. Use type instead.
And don’t worry too much about the implementation details in Python.
I have not had to deal with issues around this myself. You probably won’t either, and if you really do, you should know enough not to be looking to this answer for what to do.
Conclusion
In Python, you can check the data type of a variable or value using the built-in type() function.