[Python skill tree co-construction] Assertion

What are Python Assertions

Python assertion, that is, the Python assert statement, is simply understood as a simplified version of the if statement, which
is used to determine the value of an expression. If the result is True, the program runs. Otherwise, the program stops running and throws AssertionErroran error .

The syntax format is as follows:

assert 表达式

An analogy to the if statement is as follows:

if not 表达式:
	raise AssertionError

After the assertexpression , you can add a parameter [, arguments], and the equivalent if statement looks like this:

if not 表达式:
	raise AssertionError(arguments)

how to use

Simulation scene

In the game, set a feature that prohibits access for those under 18 years old.

def overage18(age):
    assert age >= 18, "对不起未满18岁,无法进行游戏"
    print("享受欢乐游戏时光")

if __name__ == '__main__':
    overage18(15)

But this case is not a perfect case, because the assertion is to inform the developer that an exception has occurred in the program you wrote.
If a potential error can be considered before the program is written, such as a network outage while the program is running, the use of assertions is not required in this scenario.

Assertions are mainly born for debugging assistance, for program self-checking, not for handling errors. Program bugs still rely on try...except to solve.

Since assertions are for developers , the assertions in the following cases are valid.

def something():
	"""该函数执行了很多操作"""
	my_list = [] # 声明了一个空列表
	# do something
	return my_list

def func():
	"""调用 something 函数,基于结果实现某些逻辑"""
	ret = something()
	assert len(ret) == 18, "列表元素数量不对"
	# 完成某些操作

Be careful when using assertions:
don't use assertions to validate user input, this is because when python is run from the command line, if you add the -Oflag , assertions are globally disabled and all your validation is lost.

Common Assertion Functions

  • assertEqual(a,b,msg=msg): Determine whether two values ​​are equal;
  • assertNotEqual(a,b,msg=msg): the opposite of the previous function;
  • self.assertTrue(a,msg=none): Determine whether the variable is True;
  • assertFalse(a,msg=none): same as above;
  • assertIsNone(obj=''): Determine whether obj is empty;
  • assertIsNotNone(obj=''): same as above;

There are other functions, you can retrieve data arbitrarily, and it is very easy to master the relevant usage.

expand knowledge

Applicable scenarios for Python assertions

Programming defensively
When we use assertions, we should catch illegal situations that shouldn't happen. Here we should pay attention to the difference between illegal situations and abnormal errors
, the latter must exist and must be dealt with. The condition after the assertion does not necessarily occur.

Verifying Assumptions
Assertions verify the programmer's assumptions , so these supposed exceptions are not necessarily triggered.

Guess you like

Origin blog.csdn.net/hihell/article/details/124381035