Assert type in python

№35 Инструкция assert / для начинающих

Инструкции assert в Python — это булевы выражения, которые проверяют, является ли условие истинным ( True ). Они определяют факты (утверждения) в программе. Assertion — это проверка, которую можно включить, а затем выключить, завершив тестирование программы.

Возьмем простой пример функции деления. Можно быть уверенным в том, что делитель не должен быть нолем. Это и указывается при тестировании. Разберем этот пример позже.

Что такое Assertion (утверждение)

Assertions (утверждения) — это инструкции, которые «утверждают» определенный кейс в программе. В Python они выступают булевыми выражениями, которые проверяют, является ли условие истинным или ложным. Если оно истинно, то программа ничего не делает и переходит к выполнению следующей строчки кода.

Но если оно ложно, то программа останавливается и возвращает ошибку.

Следующий синтаксис — это базовая структура инструкций утверждения в Python.

Читайте также:  Градиентный спуск python код

Если же нужно добавить сообщение для вывода при ложном условии, то синтаксис будет таким.

Это сообщение позволит лучше понять, почему код не сработал.

Пример assert

Если нужно симулировать или выполнить отладку кода, чтобы узнать, что именно происходит на определенном этапе, то «утверждения» в Python отлично для этого подходят.

Именно инструмент отладки останавливает программу, как только возникает какая-то ошибка. Он также показывает, где именно она произошла.

  • Инструкция assert принимает выражение и необязательное сообщение;
  • Она используется для проверки типов, значений аргумента и вывода функции;
  • А также для отладки, поскольку приостанавливает программу в случае ошибки.

Вот пример работы утверждений в Python.

 
def avg(ranks):
assert len(ranks) != 0
return round(sum(ranks)/len(ranks), 2)

ranks = [62, 65, 75]
print("Среднее значение:", avg(ranks))

В этом примере нужно, чтобы пользователь не оставлял параметры пустыми. Если этого не сделать, вернется ошибка Assertion Error . Вот пример вывода:

В этом случае параметры были переданы, поэтому функция вернула нужный результат.

Теперь попробуем ничего не передавать.

 
def avg(ranks):
assert len(ranks) != 0
return round(sum(ranks)/len(ranks), 2)

ranks = []
print("Среднее значение:", avg(ranks))

Длина массива ranks оказалась 0, и python вернул ошибку Assertion Error .

Traceback (most recent call last): File "C:/Users/asd/AppData/Local/Programs/Python/Python38/wb.py", line 6, in print("Среднее значение:", avg(ranks)) File "C:/Users/asd/AppData/Local/Programs/Python/Python38/wb.py", line 2, in avg assert len(ranks) != 0 AssertionError

Исключения Assertion Error можно перехватывать и обрабатывать как и любые другие исключения с помощью try-except. Но если их обработать неправильно, то программа остановится и вернет traceback .

Однако в примере выше она не возвращает ошибку с нужным сообщением. Ее можно написать самостоятельно. Вот как это делается.

 
def avg(ranks):
assert len(ranks) != 0, 'Список ranks не должен быть пустым'
return round(sum(ranks)/len(ranks), 2)

ranks = []
print("Среднее значение:", avg(ranks))

Вторым аргументом к assert в примере выше было передано сообщение, которое позже появится в выводе.

Traceback (most recent call last): File "C:/Users/asd/AppData/Local/Programs/Python/Python38/wb.py", line 6, in print("Среднее значение:", avg(ranks)) File "C:/Users/asd/AppData/Local/Programs/Python/Python38/wb.py", line 2, in avg assert len(ranks) != 0, 'Список ranks не должен быть пустым' AssertionError: Список ranks не должен быть пустым

Assert с сообщением об ошибки

Рассмотрим еще один пример с делением на 0.

 
def divide(x, y):
assert y != 0 , 'Нельзя делить на 0'
return round(x/y, 2)

z = divide(21,3)
print(z)

a = divide(21,0)
print(a)

В этом примере, если делителем будет ноль, то assert вернет сообщение с ошибкой. Посмотрим на вывод.

7.0 Traceback (most recent call last): File "C:/Users/asd/AppData/Local/Programs/Python/Python38/wb.py", line 8, in a = divide(21,0) File "C:/Users/asd/AppData/Local/Programs/Python/Python38/wb.py", line 2, in divide assert y != 0 , 'Нельзя делить на 0' AssertionError: Нельзя делить на 0 

На третьей сверху строчке написана сама инструкция assert . Именно здесь проверяется, не является ли переменная y равной 0. Если она больше 0, то условие истинно, и код возвращает требуемый результат.

Но если вызвать метод division() со вторым аргументом 0, то условие assert будет ложным.

По этой причине и возникает исключение Assertion Error . Именно оно возвращает ошибку с сообщением «Нельзя делить на 0».

Методы assert

Метод Проверка на Работает с
assertEqual(x, y) x == y
assertNotEqual(x, y) x != y
assertTrue(x) bool(x) равно True
assertFalse(x) bool(x) равно False
assertIs(x, y) x это y 3.1
assertIsNot(x, y) x это не y 3.1
assertIsNone(x) x это None 3.1
assertIsNotNone(x) x это не None 3.1
assertIn(x, y) x в y 3.1
assertNotIn(x, y) x не в y 3.1
assertIsInstance(x, y) isinstance(x, y) 3.2
assertNotIsInstance(x,y) не isinstance(x, y) 3.2

Как проверить, что функция возвращает исключение

Можно использовать TestCase.assertRaises (или TestCase.failUnlessRaises ) из модуля unittest .

 
import unittest def broken_function():
raise Exception('Это ошибка') class MyTestCase(unittest.TestCase):
def test(self):
with self.assertRaises(Exception) as context:
broken_function()

self.assertTrue('Это ошибка' in str(context.exception)) if __name__ == '__main__':
unittest.main()

Распространенные ошибки

Есть два важных момента касательно утверждений в Python, о которых нужно помнить.

  1. Не стоит использовать assert для валидации данных, ведь это приводит к появлению проблем с безопасностью и багов.
  2. Важно не писать такие утверждения, которые всегда будут истинными.

Ключевые моменты assert в Python

  1. Утверждение (Assertion) — это условие или булево выражение, которое должно быть истинным.
  2. Инструкция assert принимает выражение и необязательное сообщение.
  3. Инструкция assert используется для проверки типов, значений аргументов и вывода функций.
  4. Это также инструмент для отладки, ведь он останавливает программу при появлении ошибки.
  5. В первую очередь утверждения используются для уведомления разработчиков о неотслеживаемых ошибках. Они не должны сообщать об условия ошибок, таких как «файл не был найден», где пользователь может попытаться исправиться и повторить действия.
  6. Утверждения — это внутренняя проверка для программы. Они работают за счет объявления невозможных условий в коде. Если эти условия не проходят, значит имеется баг.

Источник

How to Check Data Type in Python | Type() Function & More

check data type python

Python has many built-in functions. In this tutorial, we will be discussing how to check the data type of the variables in python by using type(). As while programming in Python, we came to a situation where we wanted to check the data-type of the variable we use type() function. This article will help you understand the concept of type() function.

What is type() function?

Python type() is a built-in function that helps you find the class type of the variable given as input. You have to just place the variable name inside the type() function, and python returns the datatype.

Mostly, We use it for debugging purposes. we can also pass three arguments to type(), i.e., type(name, bases, dict). In such a case, it will return you a new type of object.

Syntax

Parameter

The object argument is the required parameter to be passed inside the type() function. The argument can be string, integer, list, tuple, set, dictionary, float, etc.

Syntax

Parameter

  • name: It is the name of the class.
  • bases: It is the optional parameter, and it is the name of the base class.
  • dict: It is an optional parameter, and it is the namespace that has a definition of the class.

Return value

  • If we pass only the object as the parameter, it will only return the object’s type.
  • If we pass the name, bases, and dict as the parameter, it will return the new type.

Examples to Check Data Type in Python

Let us discuss certain ways through which we can print the datatype of the variable.

1. Using type(object) Method to Check Data Type in Python

In this example, we will be taking the input in all the forms to write the variable like string, integer, negative value, float value, complex number, list, tuple, set, and dictionary. After that, we will print the data type of all the variables and see the output.

#taking input str = 'Python pool' print('Datatype : ',type(str)) num = 100 print('Datatype : ',type(num)) neg = -20 print('Datatype : ',type(neg)) float = 3.14 print('Datatype : ',type(float)) complex = 2 + 3j print('Datatype : ',type(complex)) lst = [1,2,3,4,5] print('Datatype : ',type(lst)) Tuple = (1,2,3,4,5) print('Datatype : ',type(Tuple)) Dict = print('Datatype : ',type(Dict)) set = print('Datatype : ',type(set))
Datatype : Datatype : Datatype : Datatype : Datatype : Datatype : Datatype : Datatype : Datatype :

Explanation:

First, we declare the variables and then check the type using the type() function.

2. Using type(name, bases, dict) method to Check Data Type in Python

In this example, we will be taking all the parameters like name, bases, and dict. after that, we will print the output. Let see more clearly with the help of the program.

class Python: x = 'python pool'' y = 100 t1 = type('NewClass', (Python,), dict(x='Python pool', y=100)) print(type(t1)) print(vars(t1))

Explanation:

  • Firstly, we have taken a class, Python.
  • Then, we have taken a string and integer value inside the class python.
  • Then, we have taken a variable as t1 in which we have applied the type() with the parameter as name, bases, and dict
  • After that, we have printed the type of t1 and vars of t1.
  • At last, you can see the output.

Difference between type() and isinstance()

Type() Function

Python type() is a built-in function that helps you find the class type of the variable given as input.

Isinstance() Function

Python isinstance() function is used to check if the object (first argument) is an instance or subclass of classinfo class (second argument).

Example of type() and isinstance() function

In this example, we will be discussing about both the functions and explained in detail.

age = 100 print("Datatype : ",type(age)) age = isinstance(100,int) print("age is an integer:", age)
Datatype : age is an integer: True

Explanation:

  • Firstly, we have taken age as a variable with a value equal to 100.
  • Then, we have printed the datatype of the age value.
  • After that, we have applied isinstance() function with two parameters as the value of age and type of age.
  • At last, we have printed the output.
  • By seeing the output, we can see the difference between the type and isinstance function.

Checking Array Data Type (using if hasattr(N, “_len_”))

You can check the array data type using hasattr() function in python by specifying the function. For this you need to know the functions of the array. Here, __len__ provides the length of the data which you have passed. So if hasattr can determine a function that belongs to the array, we can call it array data type. Here, the function which we’ll use is __len__.

arr=[1,2,3] if hasattr(arr, '__len__'): print('array found') else: print('not found') #array found (Output)

Here, the __len__ function determined the length of the arr that was passed as an argument. This function belongs to array data type so we used ‘if’ to see if this attribute is present in array.

Checking for datatype of variable, else raise error (Using assert)

It is used just like ‘raise’ to throw an exception but here, a condition is also specified.

x = 'abc' print(type(x)) assert type(x) != int, 'x is an integer' print('x is not an integer')

Check if data type is boolean python

We can assess whether the given data belongs to boolean or not. In this case, you will put either True or False as the input to get a boolean type.

The type function is an easy-to-use tool to find the data type in Python.

Check data type Python Dataframe

To find the data type for a dataframe in python, you may use the dtype function.

import pandas as pd df = pd.DataFrame() print("DataFrame:") print(df) result = df.dtypes print("Output:") print(result) #Make sure that all the columns have the same size

And you will obtain the given output

DataFrame: A C 0 10 1.30 1 11 0.23 Output: A int64 C float64 dtype: object

FAQs

It is a function that helps to find out the data type of the attributes of a dataframe object in python.

We can check it using the type function.
var = 4 if type(var)==int: print(“Numeric”) else: print(“Not numeric”)

Conclusion

In this tutorial, we have learned how to check the variable’s data type by using type() with two different parameters. We have also explained all the variables using type() with examples explained in detail.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Источник

Оцените статью