Skip to main content
 首页 » 编程设计

python之如何在 Python 中执行断言自省(introspection)

2024年10月17日8duanxz

我正在研究如何以相同的方式在 Python 中执行断言内省(introspection) that py.test does .例如……

>>> a = 1 
>>> b = 2 
>>> assert a == b 
Traceback (most recent call last): 
 File "<stdin>", line 1, in <module> 
AssertionError   # <--- I want more information here, eg 'AssertionError: 1 != 2' 

我看到 py.code 库 has some functionality around this我也看到了this answer ,注意到 sys.excepthook 允许你插入任何你想要的异常行为,但我不清楚如何将它们放在一起。

请您参考如下方法:

如果你想显示详细的错误信息,你可以这样做

def assertion(a,b): 
    try: 
        assert a==b 
    except AssertionError as e: 
        e.args += ('some other', 'information',) 
        raise 
 
a=1 
b=2 
assertion(a,b) 

此代码将给出此输出:

Traceback (most recent call last): 
  File "tp.py", line 11, in <module> 
    assertion(a,b) 
  File "tp.py", line 4, in assertion 
    assert a==b 
AssertionError: ('some other', 'information')