Get Variable Type Python
Introduction | |
Difference betwwen type() and isinstance() | |
type() | |
Example with type() | |
isinstance() | |
Example with isinstance() | |
Check whole list or other iterable | |
In other languages | |
Related Articles |
Introduction
Python has two functions type() and isinstance() that can be easily used to check variable' datatype.
Difference between type() and isinstance()
type() returns type of and object
isinstance() returns boolean value - if object is of specified type or not.
type()
Built-in type() function is the obvious solution to check the datatype.
It can be used in the following way.
print(type(variable))
Example with type()
There are fourteen datatypes in Python.
Let' start with three numeric types:
- int (signed integers)
- float (вещественные числа с плавающей точкой)
- complex (комплексные числа)
Создайте три переменные разного численного типа и проверьте работу функции:
var_int = 1380
var_float = 3.14
var_complex = 2.0-3.0j
print(type(var_int))
print(type(var_float))
print(type(var_complex))
<class 'int'> <class 'float'> <class 'complex'>
Рассмотрим ещё несколько примеров
# Text Type:
var_str = 'heihei.ru'
# Boolean Type:
var_bool = True
# Sequence Types:
var_list = ['heihei.ru','topbicycle.ru','eth1.ru']
var_tuple = ('aredel.com', 'aredel.com')
var_range = range(0,9)
print(type(var_str))
print(type(var_bool))
print(type(var_list))
print(type(var_tuple))
print(type(var_range))
<class 'str'> <class 'bool'> <class 'list'> <class 'tuple'> <class 'range'>
Спецификацию функции type() вы можете прочитать на сайте docs.python.org
Команда type
Есть ещё полезная команда type которая решает другую задачу.
С помощью команды
type
можно, например, определить куда установлен Python.
Подробнее об этом можете прочитать
здесь
type python3
python3 is hashed (/usr/bin/python3)
type python
python3 is hashed (/usr/bin/python)
isinstance()
Кроме type() в Python есть функция isinstance(),
с помощью которой можно проверить не относится ли
переменная к какому-то определённому типу.
Иногда это очень удобно, а если нужно - всегда можно на основе
isinstance() написать свою функцию.
Пример использования
Из isinstance() можно сделать аналог type()
Упростим задачу рассмотрев только пять типов данных, создадим пять переменных разного
типа и проверим работу функции
var_int = 1380
var_str = 'heihei.ru'
var_bool = True
var_list = ['heihei.ru','topbicycle.ru','eth1.ru']
var_tuple = ('aredel.com', 'aredel.com')
if (isinstance(var_int, int)):
print(f"{var_int} is int")
else:
print(f"{var_int} is not int")
if (isinstance(var_str, str)):
print(f"{var_str} is str")
else:
print(f"{var_str} is not str")
if (isinstance(var_bool, bool)):
print(f"{var_bool} is bool")
else:
print(f"{var_bool} is not bool")
if (isinstance(var_list, list)):
print(f"{var_list} is list")
else:
print(f"{var_list} is not list")
if (isinstance(var_tuple, tuple)):
print(f"{var_tuple} is tuple")
else:
print(f"{var_tuple} is not tuple")
Результат
1380 is int heihei.ru is str True is bool ['heihei.ru', 'topbicycle.ru', 'eth1.ru'] is list ('aredel.com', 'aredel.com') is tuple
Напишем свою фукнцию по определению типа typeof() на базе isinstance
def typeof(your_var):
if (isinstance(your_var, int)):
return 'int'
elif (isinstance(your_var, bool)):
return 'bool'
elif (isinstance(your_var, str)):
return 'str'
elif (isinstance(your_var, list)):
return 'list'
elif (isinstance(your_var, tuple)):
return 'tuple'
else:
print("type is unknown")
Протестируем нашу функцию
print(f"var_list is {typeof(var_list)}")
var_list is list
В других языках
- Си : такой функции нет.
-
C++
:
похожую задачу решает функция
typeid()
Читать статью: «Как определить тип переменной C++»
- C# : есть похожая функция GetType()
- Go : функция typeof() доступна из библиотеки reflect
- Java : оператор instanceof