如何更改 Python AssertionError 中的消息?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3807694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change the message in a Python AssertionError?
提问by Andres Jaan Tack
I'm writing per the following, in which I try to produce a decent error message when comparing two multiline blocks of Unicode text. The interior method that does the comparison raises an assertion, but the default explanation is useless to me
我正在根据以下内容进行编写,其中在比较两个多行 Unicode 文本块时,我尝试生成一个不错的错误消息。进行比较的内部方法提出了一个断言,但默认的解释对我来说是无用的
I need to add something to code such as this below:
我需要在代码中添加一些内容,如下所示:
def assert_long_strings_equal(one, other):
lines_one = one.splitlines()
lines_other = other.splitlines()
for line1, line2 in zip(lines_one, lines_other):
try:
my_assert_equal(line1, line2)
except AssertionError, error:
# Add some information to the printed result of error??!
raise
I cannot figure out how to change the printed error message in the assertionerror I catch. I always get AssertionError: u'something' != 'something else', which only shows the first line of the output.
我无法弄清楚如何更改我捕获的断言错误中打印的错误消息。我总是得到AssertionError: u'something' != 'something else',它只显示输出的第一行。
How can I change the assertion message to print out whatever I want?
如何更改断言消息以打印出我想要的任何内容?
If it's relevant, I am using noseto run the test.
如果相关,我将nose用于运行测试。
采纳答案by Honza Javorek
Use e.args, e.messageis deprecated.
使用e.args,e.message已弃用。
try:
assert False, "Hello!"
except AssertionError as e:
e.args += ('some other', 'important', 'information', 42)
raise
This preserves the original traceback. Its last part then looks like this:
这保留了原始回溯。它的最后一部分看起来像这样:
AssertionError: ('Hello!', 'some other', 'important', 'information', 42)
Works in both Python 2.7 and Python 3.
适用于 Python 2.7 和 Python 3。
回答by zchtodd
You can pass the desired message when creating the exception.
您可以在创建异常时传递所需的消息。
raise AssertionError(line1 + ' != ' + line2)
Hope this helps.
希望这可以帮助。
回答by Katriel
assert expression, info
For instance,
例如,
>>> assert False, "Oopsie"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: Oopsie
From the docs:
从文档:
Assert statements are a convenient way to insert debugging assertions into a program:
assert_stmt ::= "assert" expression ["," expression]The simple form,
assert expression, is equivalent toif __debug__: if not expression: raise AssertionErrorThe extended form
assert expression1, expression2is equivalent to
if __debug__: if not expression1: raise AssertionError(expression2)These equivalences assume that
__debug__andAssertionErrorrefer to the built-in variables with those names. In the current implementation, the built-in variable__debug__is True under normal circumstances, False when optimization is requested (command line option -O). The current code generator emits no code for an assert statement when optimization is requested at compile time. Note that it is unnecessary to include the source code for the expression that failed in the error message; it will be displayed as part of the stack trace.
断言语句是一种将调试断言插入程序的便捷方式:
assert_stmt ::= "assert" expression ["," expression]简单的形式,
assert expression, 等价于if __debug__: if not expression: raise AssertionError扩展形式
assert expression1, expression2相当于
if __debug__: if not expression1: raise AssertionError(expression2)这些等价假设
__debug__并AssertionError引用具有这些名称的内置变量。在当前的实现中,内置变量__debug__在正常情况下为 True,在请求优化时为 False(命令行选项 -O)。当在编译时请求优化时,当前的代码生成器不会为 assert 语句发出任何代码。请注意,没有必要在错误消息中包含失败的表达式的源代码;它将作为堆栈跟踪的一部分显示。
回答by Russell Borogove
You want to take the caught exception, convert it to a string, combine it with some additional string info, and raise a new exception.
您想获取捕获的异常,将其转换为字符串,将其与一些其他字符串信息结合起来,并引发一个新的异常。
x = 3
y = 5
try:
assert( x == y )
except AssertionError, e:
raise( AssertionError( "Additional info. %s"%e ) )
回答by Antti V?yrynen
With this method I was able to edit the message and still have the stack trace (+any other information) visible. Also newlines are displayed right.
使用这种方法,我能够编辑消息并且仍然可以看到堆栈跟踪(+任何其他信息)。换行符也显示正确。
try:
my_assert_equal(line1, line2)
except AssertionError as e:
message = e.args[0]
message += "\nThis appends the default message and can have newlines"
e.args = (message,) #wrap it up in new tuple
raise

