断言是什么意思?它是如何使用的?
当前回答
>>>this_is_very_complex_function_result = 9
>>>c = this_is_very_complex_function_result
>>>test_us = (c < 4)
>>> #first we try without assert
>>>if test_us == True:
print("YES! I am right!")
else:
print("I am Wrong, but the program still RUNS!")
I am Wrong, but the program still RUNS!
>>> #now we try with assert
>>> assert test_us
Traceback (most recent call last):
File "<pyshell#52>", line 1, in <module>
assert test_us
AssertionError
>>>
其他回答
断言是一种系统的方法,用于检查程序的内部状态是否如程序员所期望的那样,目的是捕捉错误。请参阅下面的示例。
>>> number = input('Enter a positive number:')
Enter a positive number:-1
>>> assert (number > 0), 'Only positive numbers are allowed!'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: Only positive numbers are allowed!
>>>
正如其他答案所指出的,assert类似于在给定条件不为真时抛出异常。一个重要的区别是,如果使用优化选项-O编译代码,断言语句将被忽略。文档说断言表达式可以更好地描述为等效于
if __debug__:
if not expression: raise AssertionError
如果你想彻底测试你的代码,然后在你高兴地看到你的断言案例都没有失败时发布一个优化版本,这可能是有用的——当优化打开时,__debug__变量变成False,条件将停止计算。如果您依赖断言,而没有意识到断言已经消失,该特性还可以发现这一点。
assert语句几乎存在于每一种编程语言中。它有两个主要用途:
它有助于在程序的早期(原因很清楚的时候)检测问题,而不是在其他一些操作失败的时候。例如,Python中的类型错误如果没有在早期被捕获,可能会在实际引发异常之前经历几层代码。 对于阅读代码的其他开发人员来说,它可以作为文档使用,他们看到断言后可以自信地说从现在开始它的条件是成立的。
当你……
assert condition
... 您告诉程序测试该条件,如果条件为假,则立即触发一个错误。
在Python中,它大致相当于:
if not condition:
raise AssertionError()
在Python shell中试试:
>>> assert True # nothing happens
>>> assert False
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
断言可以包含可选的消息,您可以在运行解释器时禁用它们。
如果断言失败,打印一条消息:
assert False, "Oh no! This assertion failed!"
不要像调用函数一样使用括号来调用assert。这是一个声明。如果执行断言(condition, message),则运行断言时将使用(condition, message)元组作为第一个参数。
至于禁用它们,当以优化模式运行python时,其中__debug__为False, assert语句将被忽略。只需要传递-O标志:
python -O script.py
相关文档请参见这里。
如果assert后的语句为真,则程序继续执行,但如果assert后的语句为假,则程序报错。就这么简单。
例如:
assert 1>0 #normal execution
assert 0>1 #Traceback (most recent call last):
#File "<pyshell#11>", line 1, in <module>
#assert 0>1
#AssertionError
def getUser(self, id, Email):
user_key = id and id or Email
assert user_key
可用于确保在函数调用中传递参数。
推荐文章
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 断言是邪恶的吗?