断言是什么意思?它是如何使用的?


当前回答

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

相关文档请参见这里。

其他回答

其他人已经为您提供了文档链接。

您可以在交互式shell中尝试以下操作:

>>> assert 5 > 2
>>> assert 2 > 5
Traceback (most recent call last):
  File "<string>", line 1, in <fragment>
builtins.AssertionError:

第一个语句什么都不做,而第二个语句引发异常。这是第一个提示:断言用于检查在代码的给定位置(通常是函数的开始(前置条件)和结束(后置条件)中应该为真条件。

断言实际上与契约编程高度相关,这是一种非常有用的工程实践:

http://en.wikipedia.org/wiki/Design_by_contract。

从文档:

断言语句是向程序中插入调试断言的一种方便方法

你可以在这里阅读更多:http://docs.python.org/release/2.5.2/ref/assert.html

>>>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
>>> 

这是一个简单的例子,保存到文件(比如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语句几乎存在于每一种编程语言中。它有助于在程序的早期(原因很清楚的时候)检测问题,而不是在稍后作为其他操作的副作用检测问题。他们总是期待一个真实的条件。

当你这样做的时候:

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通常由程序员在不与用户直接交互的库或模块上使用。