If we want to determine a data type of variable in Python (such as int
, float
, bool
, str
... etc), we may be use isinstance()
function instead of type()
function.
This is because isinstance()
runs faster and also supports the comparison of class objects, which is better in all aspects.
The following is to record the usage of isinstance()
.
How to use isinstance() function
The usage way is very simple.
a = 123 print(isinstance(a, int)) print(isinstance(a, str)) print(isinstance(a, (int, str, float)))
Output:
True
False
True
Simply put, the first parameter is the "variable" we want to query, and the second parameter is the "data type" we want to confirm. However, as seen in the third example, we can also enter multiple "data types" to confirm whether the variable type is in it.
As for why isinstance()
is better than type()
to confirm the data type? Let's look at an example below.
import time def type_test(): start_time = time.time() a = 123 b = 'test' c = list(b) print(type(a) == int) print(type(b) == int) print(type(c) == int) print('type time: {}'.format(time.time()-start_time)) print('='*70) def isinstance_test(): start_time = time.time() a = 123 b = 'test' c = list(b) print(isinstance(a, int)) print(isinstance(b, int)) print(isinstance(c, int)) print('isinstance time: {}'.format(time.time()-start_time)) print('='*70) if __name__ == '__main__': type_test() isinstance_test()
Output:
True
False
False
type time: 3.5762786865234375e-05
==============================================
True
False
False
isinstance time: 1.5020370483398438e-05
==============================================
I ran it several times, and every time isinstance()
was faster than using type()
to confirm the data type.