断言是什么意思?它是如何使用的?
当前回答
assert语句几乎存在于每一种编程语言中。它有助于在程序的早期(原因很清楚的时候)检测问题,而不是在稍后作为其他操作的副作用检测问题。他们总是期待一个真实的条件。
当你这样做的时候:
assert condition
您告诉程序测试该条件,如果为假,则立即触发错误。
在Python中,assert表达式等价于:
if __debug__:
if not <expression>: raise AssertionError
你可以使用扩展表达式来传递一个可选的消息:
if __debug__:
if not (expression_1): raise AssertionError(expression_2)
在Python解释器中试试:
>>> assert True # Nothing happens because the condition returns a True value.
>>> assert False # A traceback is triggered because this evaluation did not yield an expected value.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
在使用它们之前有一些注意事项,主要是针对那些认为在assert和if语句之间切换的人。使用assert的目的是在某些情况下,当程序验证一个条件并返回一个值时,应该立即停止程序,而不是采取其他方法来绕过错误:
1. 括号
您可能已经注意到,assert语句使用了两个条件。因此,不要用圆括号把它们括起来作为一个明显的建议。如果你这样做:
assert (condition, message)
例子:
>>> assert (1==2, 1==1)
<stdin>:1: SyntaxWarning: assertion is always true, perhaps remove parentheses?
你将使用(condition, message)运行断言,它表示一个元组作为第一个参数,这是因为Python中的非空元组总是True。但是,你可以单独做,没有问题:
assert (condition), "message"
例子:
>>> assert (1==2), ("This condition returns a %s value.") % "False"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: This condition returns a False value.
2. 调试的目的
如果你想知道什么时候使用assert语句。举一个现实生活中的例子:
*当你的程序倾向于控制用户输入的每个参数时:
def loremipsum(**kwargs):
kwargs.pop('bar') # return 0 if "bar" isn't in parameter
kwargs.setdefault('foo', type(self)) # returns `type(self)` value by default
assert (len(kwargs) == 0), "unrecognized parameter passed in %s" % ', '.join(kwargs.keys())
*另一种情况是在数学中,0或非正作为某个方程的系数或常数:
def discount(item, percent):
price = int(item['price'] * (1.0 - percent))
print(price)
assert (0 <= price <= item['price']),\
"Discounted prices cannot be lower than 0 "\
"and they cannot be higher than the original price."
return price
*甚至是一个简单的布尔实现的例子:
def true(a, b):
assert (a == b), "False"
return 1
def false(a, b):
assert (a != b), "True"
return 0
3.数据处理或数据验证
最重要的是不要依赖assert语句来执行数据处理或数据验证,因为该语句可以在Python初始化时使用- o或- oo标记(分别表示值1、2和0(默认值))或PYTHONOPTIMIZE环境变量关闭。
价值1:
* assert被禁用;
*字节码文件使用.pyo而不是.pyc扩展名生成;
* sys.flags.optimize设置为1 (True);
*和,__debug__被设置为False;
值2:禁用一个东西
*文档字符串被禁用;
因此,使用assert语句来验证一种预期的数据是极其危险的,甚至意味着存在一些安全问题。然后,如果你需要验证一些权限,我建议你提出AuthError代替。作为有效的前置条件,assert通常由程序员在不与用户直接交互的库或模块上使用。
其他回答
这是一个简单的例子,保存到文件(比如b.py)
def chkassert(num):
assert type(num) == int
chkassert('a')
当$python b.py
Traceback (most recent call last):
File "b.py", line 5, in <module>
chkassert('a')
File "b.py", line 2, in chkassert
assert type(num) == int
AssertionError
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 condition
您告诉程序测试该条件,如果为假,则立即触发错误。
在Python中,assert表达式等价于:
if __debug__:
if not <expression>: raise AssertionError
你可以使用扩展表达式来传递一个可选的消息:
if __debug__:
if not (expression_1): raise AssertionError(expression_2)
在Python解释器中试试:
>>> assert True # Nothing happens because the condition returns a True value.
>>> assert False # A traceback is triggered because this evaluation did not yield an expected value.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
在使用它们之前有一些注意事项,主要是针对那些认为在assert和if语句之间切换的人。使用assert的目的是在某些情况下,当程序验证一个条件并返回一个值时,应该立即停止程序,而不是采取其他方法来绕过错误:
1. 括号
您可能已经注意到,assert语句使用了两个条件。因此,不要用圆括号把它们括起来作为一个明显的建议。如果你这样做:
assert (condition, message)
例子:
>>> assert (1==2, 1==1)
<stdin>:1: SyntaxWarning: assertion is always true, perhaps remove parentheses?
你将使用(condition, message)运行断言,它表示一个元组作为第一个参数,这是因为Python中的非空元组总是True。但是,你可以单独做,没有问题:
assert (condition), "message"
例子:
>>> assert (1==2), ("This condition returns a %s value.") % "False"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: This condition returns a False value.
2. 调试的目的
如果你想知道什么时候使用assert语句。举一个现实生活中的例子:
*当你的程序倾向于控制用户输入的每个参数时:
def loremipsum(**kwargs):
kwargs.pop('bar') # return 0 if "bar" isn't in parameter
kwargs.setdefault('foo', type(self)) # returns `type(self)` value by default
assert (len(kwargs) == 0), "unrecognized parameter passed in %s" % ', '.join(kwargs.keys())
*另一种情况是在数学中,0或非正作为某个方程的系数或常数:
def discount(item, percent):
price = int(item['price'] * (1.0 - percent))
print(price)
assert (0 <= price <= item['price']),\
"Discounted prices cannot be lower than 0 "\
"and they cannot be higher than the original price."
return price
*甚至是一个简单的布尔实现的例子:
def true(a, b):
assert (a == b), "False"
return 1
def false(a, b):
assert (a != b), "True"
return 0
3.数据处理或数据验证
最重要的是不要依赖assert语句来执行数据处理或数据验证,因为该语句可以在Python初始化时使用- o或- oo标记(分别表示值1、2和0(默认值))或PYTHONOPTIMIZE环境变量关闭。
价值1:
* assert被禁用;
*字节码文件使用.pyo而不是.pyc扩展名生成;
* sys.flags.optimize设置为1 (True);
*和,__debug__被设置为False;
值2:禁用一个东西
*文档字符串被禁用;
因此,使用assert语句来验证一种预期的数据是极其危险的,甚至意味着存在一些安全问题。然后,如果你需要验证一些权限,我建议你提出AuthError代替。作为有效的前置条件,assert通常由程序员在不与用户直接交互的库或模块上使用。
格式: 断言表达式(参数) 当assert遇到语句时,Python对表达式求值。如果语句不为真,则引发异常(assertionError)。 如果断言失败,Python使用ArgumentExpression作为AssertionError的参数。可以像使用try-except语句一样捕获和处理AssertionError异常,但如果没有处理,它们将终止程序并产生跟踪。 例子:
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
print KelvinToFahrenheit(-5)
当执行上面的代码时,它会产生以下结果:
32.0
451
Traceback (most recent call last):
File "test.py", line 9, in <module>
print KelvinToFahrenheit(-5)
File "test.py", line 4, in KelvinToFahrenheit
assert (Temperature >= 0),"Colder than absolute zero!"
AssertionError: Colder than absolute zero!
从文档:
断言语句是向程序中插入调试断言的一种方便方法
你可以在这里阅读更多:http://docs.python.org/release/2.5.2/ref/assert.html
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录