我正在尝试实现一个断言函数。如何将失败条件的文本放入错误消息中?如果我必须从回溯中解析它,我可以依赖任何关于帧格式的东西吗?
答案 0 :(得分:3)
AssertionError就像python中的任何其他异常一样,assert
是一个等同于
if __debug__:
if not expression: raise AssertionError
或
if __debug__:
if not expression1: raise AssertionError(expression2)
因此您可以在断言中添加第二个参数以获得额外的输出
from sys import exc_info
from traceback import print_exception
# assertions are simply exceptions in Python
try:
assert False, "assert was false"
except AssertionError:
print_exception(*exc_info())
输出
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
AssertionError: assert was false
答案 1 :(得分:2)
如果您确定要测试的表达式是安全的,您可以执行以下操作:
档案my_assert.py:
import sys
def my_assert(condition):
caller = sys._getframe(1)
if not eval(condition, caller.f_globals, caller.f_locals):
raise AssertionError(repr(condition) + " on line " +
str(caller.f_lineno) + ' in ' +
caller.f_code.co_name)
文件test_my_assert.py:
from my_assert import my_assert
global_var = 42
def test():
local_var = 17
my_assert('local_var*2 < global_var') # OK
my_assert('local_var > global_var')
test()
输出:
Traceback (most recent call last):
File "test_my_assert.py", line 10, in <module>
test()
File "test_my_assert.py", line 8, in test
my_assert('local_var > global_var')
File "my_assert.py", line 8, in my_assert
caller.f_code.co_name)
AssertionError: 'local_var > global_var' on line 8 in test
答案 2 :(得分:0)
我非常苛刻的解决方案:
def my_assert(condition):
if not eval(condition):
# error stuff
然后通过将条件放在引号中来使用它。然后是一个可以在错误消息中打印的字符串。
或者,如果您希望它实际提出AssertionError
:
def my_assert(condition):
if not eval(condition):
raise AssertionError(condition)