Assert
An assert statement is used for debugging and internal consistency checks.
Introduction
An assertion is a boolean expression at a specific point in a program that will be true unless there is a bug in the program.
An assertion could simply be a comment used by the programmer to think about how the code works. Or an assertion could document a constraint on the system. (See also: ExceptionsAsConstraints).
However, it is often possible to actually compile the assertion to code and let it be executed in context to see if the statement it makes really does hold. When programmers talk about assertions, they usually mean this kind of executed assertion.
Python provides the assert statement for this purpose.
The assert statement in Python is a debugging aid that tests a condition:
- If the condition is true, nothing happens, and your program continues to run.
- If the condition is false, Python raises an
AssertionErrorexception, immediately stopping the program.
Here’s a simple example:
= -100
: =
assert 0 <= < , fAs long as the index is within the range specified, this statement is a no-op.
If the index is out of range, however, the assertion will terminate the application and display the failed boolean expression as well as the filename and line number of the assertion in the source code.
Traceback (most recent call last):
File "C:\Users\david\Workspace\uniprot\tmp.py", line 4, in <module>
assert 0 <= index < len(items), f"{index} is out of bounds"
^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: -100 is out of boundsThe diagnostic information printed by a failed assertion (not to mention the potentially dramatic act of terminating the offending program) is not very end-user-friendly.
This goes to an important point: assertions are not an error-handling mechanism. The purpose of an assertion is not to handle an error, it is to (ultimately) notify a programmer of an error so that he can fix it.
Since assertions that don’t fail are no-ops, once a program has been thoroughly tested and bug-fixed, it is possible to recompile the source code without the assertions to produce a program that is both smaller and faster; for programs that make heavy use of assertions, this can result in a significant difference in performance.
When an assertion fails, the program halts, and a programmer figures out what’s wrong, and fixes it. Then the assertion doesn’t fail anymore. It’s important to understand that the code is not supposed to handle the error - a person is.
It is also important to remember that standard operating procedure for assertions is to turn them off before doing a build that will be sent to real customers.
Basic Syntax
The syntax for assert is simple:
assert , Estás leyendo una vista previa.
Inicia sesión para leer el artículo completo. Cualquier cuenta abre 4 artículos gratuitos al mes; el alumnado y el profesorado leen las páginas de su curso sin límite.
Iniciar sesión