“断言"的使用是什么?在Python中? [英] What is the use of "assert" in Python?
问题描述
我一直在阅读一些源代码,并且在几个地方看到了assert
的用法.
I have been reading some source code and in several places I have seen the usage of assert
.
这到底是什么意思?它的用途是什么?
What does it mean exactly? What is its usage?
推荐答案
assert
语句几乎存在于每种编程语言中.它有助于在程序中尽早发现问题,找出原因所在,而不是在其他操作后再发现问题.
The assert
statement exists in almost every programming language. It helps detect problems early in your program, where the cause is clear, rather than later as a side-effect of some other operation.
当你做...
assert condition
...您要告诉程序测试该条件,如果条件为假,则立即触发错误.
... you're telling the program to test that condition, and immediately trigger an error if the condition is false.
在Python中,它大致等效于此:
In Python, it's roughly equivalent to this:
if not condition:
raise AssertionError()
在Python shell中尝试一下:
Try it in the Python shell:
>>> assert True # nothing happens
>>> assert False
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
断言可以包含可选消息,您可以在运行解释器时将其禁用.
Assertions can include an optional message, and you can disable them when running the interpreter.
要在断言失败时打印一条消息:
To print a message if the assertion fails:
assert False, "Oh no! This assertion failed!"
不要不要像函数一样使用括号来调用assert
.这是一个声明.如果您执行assert(condition, message)
,则将以(condition, message)
元组作为第一个参数运行assert
.
Do not use parenthesis to call assert
like a function. It is a statement. If you do assert(condition, message)
you'll be running the assert
with a (condition, message)
tuple as first parameter.
关于禁用它们,当在优化模式下运行python
时,其中__debug__
为False
时,assert语句将被忽略.只需传递-O
标志:
As for disabling them, when running python
in optimized mode, where __debug__
is False
, assert statements will be ignored. Just pass the -O
flag:
python -O script.py
有关文档,请参见此处.
这篇关于“断言"的使用是什么?在Python中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!