Assertions of Python Advanced Grammar

Assertions of Python Advanced Grammar

In Python programming, assertions are a useful tool for examining the state of a program, which can help you find bugs in your program. Assertions are checkpoints placed in code to ensure that certain conditions of the program must be true, otherwise the program raises an error. In this article, we will discuss assertions in Python in detail with multiple examples.
insert image description here

Basic use of assertions

In Python, assertstatements are keywords used to implement assertions. Its basic syntax is as follows:

assert condition

If conditiontrue, the program continues execution; if conditionfalse, the program raises a AssertionError.

For example, we can use assertthe statement to check the input parameters of a function:

def add_positive_numbers(x, y):
    assert x > 0 and y > 0, "Both numbers must be positive"
    return x + y

In the above code, if xor yis not a positive number, the assertstatement raises a AssertionErrorwith the error message "Both numbers must be positive".

1. Boolean expressions in assert statements

The assert statement <condition>can be any Boolean expression, including complex logical expressions and function calls. For example:

a = 10
b = 20

# 判断a是否大于b的一半
assert a > b/2, "a不大于b的一半"

# 判断两个字符串是否相等
assert len("hello") == len("world"), "两个字符串长度不相等"

2. Callable objects in assert statements

The assert statement <condition>can also be a callable object, such as a function or method. In this case, the assertion verifies that the return value of the callable is true. For example:

def is_even(num):
    return num % 2 == 0

# 判断一个数是否为偶数
assert is_even(10), "这不是一个偶数"
assert not is_even(11), "这不是一个奇数"

In the above code, we defined a function is_even(num)to check whether a number is even or not. In the assertion, we call the function and verify the even and odd cases separately.

3. Iterable objects in assert statement

The assert statement <condition>can also be an iterable object, such as a list, tuple, or dictionary. In this case, the assertion verifies whether the iterable is empty or not. For example:

my_list = [1, 2, 3]

# 判断列表不为空
assert my_list, "列表不能为空"

# 删除列表中的所有元素
my_list.clear()

# 判断列表为空
assert not my_list, "列表必须为空"

In the above code, we use the list my_listas the assertion condition to verify that the list is not empty and the list is empty.

Advanced use of assertions

Assertions can be used not only to check the input parameters of a function, but also to check the output of a function, or any other state of the program. In complex programs, assertions can help you ensure the correctness of your code, especially when some parts of the code you are writing may be affected by other parts.

For example, we can use assertions to check the result of a list sort function:

def test_sort_function(sort_function):
    list = [5, 2, 9, 1]
    sorted_list = sort_function(list)
    assert sorted_list == [1, 2, 5, 9], "The sort function did not return a correctly sorted list"

In the above code, assertthe statement raises a if the result of the sort function is not the expected sorted list AssertionError.

Assertions vs Exception Handling

Although assertions and exception handling can both be used to detect and handle errors in programs, they are not used in exactly the same scenarios. In Python, assertions are often used in the development and debugging phases to catch bugs at an early stage. Assertions should be removed or disabled once the program is developed and adequately tested.

In contrast, exception handling is usually used to deal with expected errors that may occur during program execution, such as file not found errors or network connection errors. These errors are usually not caused by programming errors, but by the program's operating environment or user input.

Notes on Assertions

When using assertions, there are some points to be aware of:

  1. Don't rely too heavily on assertions to handle all errors that may arise in your program. Assertions are primarily intended for error detection during development and debugging and should not be used

  2. Handle runtime errors. In Python, exception handling should be used for possible runtime errors such as file manipulation errors, network errors, etc.

    1. Do not use expressions in assertions that may change the state of the program. Since Python has a command-line option -O(optimization mode), in this mode, assertions will be globally disabled, that is, all assert statements will be ignored and executed. Therefore, if you use an expression in an assert statement that changes the state of the program, those state changes will not occur in optimized mode, possibly resulting in inconsistent program behavior.
    # 错误的做法
    assert list.pop(0) == 0, "The first element is not zero"
    

    In the above code, list.pop(0) will be executed regardless of whether list.pop(0) == 0 is true, and this will change the contents of list. If running in optimized mode, this expression will not be executed, so the contents of list will not be changed.

    1. Assertion error messages should be as clear and specific as possible. When the assertion fails, if you can quickly determine the cause of the error through the error message, it will greatly improve the efficiency of debugging.

example

  1. 检查变量是否为 None
x = None
assert x is not None, 'x must be defined'

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-wMoBFkFF-1686875657585)(image-20230615143535937.png)]

  2. 确保列表不为空
mylist = [1, 2, 3]
assert mylist, 'The list should not be empty!'

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-744jML2X-1686875657591)(image-20230615143610641.png)]

  3. 检查字典中是否存在指定键
mydict = {
    
    'a': 1, 'b': 2}
assert 'c' in mydict, 'Key "c" not found in dictionary'

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-f8Qpw9EU-1686875657595)(image-20230615143651794.png)]

  4. 确保函数返回值符合要求
def add(a, b):
 return a + b

assert add(2, 3) == 5, 'add() function is not working correctly'

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-QZHh1jvt-1686875657596)(image-20230615143711144.png)]

  5. 检查异常是否被正确抛出
def divide(a, b):
 assert b != 0, 'Cannot divide by zero!'
 return a / b

try:
 divide(3, 0)
except AssertionError as error:
 print(error)

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-zG94ueq9-1686875657599)(image-20230615143730643.png)]

These are examples of common uses of assertions, but not all. By using assertions, problems can be found in time during the development phase, and the correctness and stability of the code can be guaranteed.

Summarize

This article introduces the basic and advanced usage of assertions in Python, as well as precautions. By using assertions, problems can be found in time during the development phase, and the correctness and stability of the code can be guaranteed. It should be noted that it is best to turn off assertions in a production environment, because this will affect the performance of the program. At the same time, do not use expressions that may change the state of the program in the assertion, and the error message of the assertion should be as clear and specific as possible.

To sum up, assertion is an important feature of Python, which can help us quickly find errors during development and debugging. Understanding and mastering the use of assertions allows us to write and debug Python programs more effectively.

Guess you like

Origin blog.csdn.net/qq_42076902/article/details/131239372