Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use assert assertions gracefully in Python

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

It is believed that many inexperienced people have no idea about how to use assert assertion gracefully in Python. Therefore, this article summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

What is assert assertion

Assert statements are a convenient way to insert debugging assertions into a program

Assertion declaration is a convenient way to debug a program. Assertions can be seen as a debug tool, and the implementation of Python conforms to this design philosophy. In Python, the execution of assert statements depends on the built-in variable _ _ debug__, whose default value is True. The assert statement is executed only when _ _ debug__ is True.

For a general declaration, assert expression is equivalent to

If _ _ debug__: if not expression: raise AssertionError

Assert can declare two expression at the same time, for example, assert expression1, expression2 is equivalent to

If _ _ debug__: if not expression1: raise AssertionError (expression2)

If the script file is executed with the-O parameter, _ _ debug__ is False

As an example, suppose we have a script testAssert.py that reads:

Print (_ _ debug__) assert 1 > 2

When running with python assert.py, _ _ debug__ outputs True,assert 1 > 2 statements and throws an AssertionError exception.

When running with python-O assert.py, _ _ debug__ outputs the False,assert 1 > 2 statement without reporting any exceptions because it is not executed.

Usage scenarios for assertions and exceptions

Let's start with the conclusion:

Check prior condition use assertion, check posterior condition use exception

To illustrate, for example, we often encounter scenarios of reading local files in development. We define a read_file method.

Def read_file (path): assert isinstance (file_path, str)...

The read_file function requires that certain conditions be met at the beginning of execution: file_path must be of type str, and this condition is a priori condition. If the condition is not met, the function cannot be called. If the condition is not met, it is proved that bug appears in the code. Then we can use the assert statement to infer the type of file_path and remind programmers to modify the code. You can also use if...raise... Statement to implement assert, but it is much more tedious. You can see the use of assert for a priori judgment in many excellent Python projects, so you can pay more attention to it at ordinary times.

After the read_file function is called and executed, certain conditions still need to be met. For example, the file specified by file_path needs to exist, and the current user has permission to read the file. These conditions are called posterior conditions. For posterior condition checking, we need to use exceptions to handle them.

Def read_file (file_path): assert isinstance (file_path, str) if not check_exist (file_path): raise FileNotFoundError () if not has_privilege (file_path): raise PermissionError ()

Files do not exist and do not have permissions. These two cases do not belong to the code bug, but are part of the code logic. After the upper code catches an exception, other logic may be executed, so we cannot accept that this part of the code is ignored in the production environment, which is a posteriori condition. Moreover, compared with the assert statement that can only throw AssertionError, using exceptions can throw more detailed errors, making it convenient for the upper code to execute different logic for different errors.

Several principles for using assertions

Use assertions to capture illegal situations that should not have occurred. Do not confuse the difference between illegal and erroneous situations, the latter is inevitable and must be dealt with.

Use assertions to confirm the parameters of the function.

When writing a function, you should examine it over and over again and ask yourself, "what assumptions am I going to make?" Once the assumptions are determined, assertions are used to check the assumptions.

General textbooks encourage programmers to design error-proof programs, but keep in mind that this programming style conceals errors. When doing error-proof programming, if something "impossible" does happen, use assertions to warn the police.

Assertions can also be used for code testing, as a unit test for a sloppy developer, as long as you can accept that the test does nothing when using the-O flag. I sometimes use "assert Fasle" in my code to mark branches that haven't been implemented yet, and of course I hope they fail. If it's a little more detailed, maybe triggering NotImplementedError is a better option.

Another good use of assertions is to check the invariants in the program. An invariant is some condition that you can believe to be true, unless a defect causes it to become false. If there is a defect, the sooner it is found, the better, so we need to test it, but we don't want to affect the speed of code execution because of these tests. Therefore, by using assertions, it can take effect at development time and fail in the product.

Assertions are also a good checkpoint comment. To replace the following comments:

# when we do this, we know that n > 2 # you can ensure that you use the following assertions at run time: assert n > 2 recommends that assertions are not used:

Do not use it to test the data provided by the user, or where you need to change the check in all cases

Do not use it to check areas where you think you may fail in normal use. Assertions are used for very special failure conditions. Your users will never see an AssertionError, and if they do, it's a bug that must be fixed.

In particular, do not use an assertion because it is smaller than an explicit test plus a trigger exception. Assertions are not a shortcut for lazy code writers.

Do not use assertions to check the input parameters of a common library, because you cannot control the caller and there is no guarantee that it will not break the contract of the function.

Do not use assertions for any errors that you expect to modify. In other words, you have no reason to catch an AssertionError exception in the product code.

Don't use assertions too much, they make the code obscure.

After reading the above, have you mastered how to use assert assertions elegantly in Python? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report