Python 断言——改进了失败的内省? [英] Python assert -- improved introspection of failure?

查看:29
本文介绍了Python 断言——改进了失败的内省?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个相当无用的断言错误;它不会告诉所涉及的表达式的值(假设使用的常量实际上是变量名):

This is a rather useless assertion error; it does not tell the values of the expression involved (assume constants used are actually variable names):

$ python -c "assert 6-(3*2)"
[...]
AssertionError

在 Python 中是否有更好的 assert 实现更花哨?它不能引入额外的执行开销(除非断言失败)..并且如果使用 -O 标志必须关闭.

Is there a better assert implementation in Python that is more fancy? It must not introduce additional overhead over execution (except when assert fails) .. and must turn off if -O flag is used.

编辑:我知道作为字符串的断言的第二个参数.我不想写一个 .. 因为它是在被断言的表达式中编码的.DRY(不要重复自己).

Edit: I know about assert's second argument as a string. I don't want to write one .. as that is encoded in the expression that is being asserted. DRY (Don't Repeat Yourself).

推荐答案

将你的函数安装为 sys.excepthook -- 见 文档.你的函数,如果第二个参数是AssertionError,可以反省你内心的内容;特别是,通过第三个参数,回溯,它可以获取断言失败的帧和确切位置,通过源或字节码获取失败的异常,所有相关变量的值等. Module inspect 有帮助.

Install your of function as sys.excepthook -- see the docs. Your function, if the second argument is AssertionError, can introspect to your heart's contents; in particular, through the third argument, the traceback, it can get the frame and exact spot in which the assert failed, getting the failing exception through the source or bytecode, the value of all relevant variables, etc. Module inspect helps.

完全通用地完成它是一项相当大的工作,但是根据您在编写 assert 的方式时愿意接受的约束,它可以大大减轻(例如将它们限制为与可能涉及闭包的非局部变量等相比,仅局部或全局变量使内省更容易.

Doing it in full generality is quite a piece of work, but depending on what constraints you're willing to accept in how you write your asserts it can be lightened substantially (e.g. restricting them to only local or global variables makes introspection easier than if nonlocal variables of a closure could be involved, and so forth).

这篇关于Python 断言——改进了失败的内省?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆