python的`assert`语句可接受的用例是什么? [英] What are acceptable use-cases for python's `assert` statement?

查看:126
本文介绍了python的`assert`语句可接受的用例是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常使用python的assert语句来检查用户输入,如果我们处于损坏状态,则会快速进行故障转移.我知道,当带-o(优化)标志的python时,断言会被删除.我个人没有以优化模式运行我的任何应用程序,但感觉我应该避免断言,以防万一.

I often use python's assert statement to check user input and fail-fast if we're in a corrupt state. I'm aware that assert gets removed when python with the -o(optimized) flag. I personally don't run any of my apps in optimized mode, but it feels like I should stay away from assert just in-case.

写起来感觉更干净

assert filename.endswith('.jpg')

if not filename.endswith('.jpg'):
    raise RuntimeError

这是否是断言的有效用例?如果没有,python assert语句的有效用例是什么?

Is this a valid use case for assert? If not, what would a valid use-case for python's assert statement be?

推荐答案

应该使用断言来表示不变量前提条件.
在您的示例中,您将使用它们来检查意外的输入-这是完全不同的 class 异常.

Assertions should be used for expressing invariants, or preconditions.
In your example, you are using them for checking unexpected input - and that's a completely different class of exceptions.

根据要求,完全可以在错误的输入上引发异常并停止应用程序;但是,应该始终针对表达量身定制代码,而提高AssertionError并不是那么明确.
更好的方法是提出您自己的异常,或者是ValueError.

Depending on the requirements, it may be perfectly OK to raise an exception on wrong input, and stop the application; however the code should always be tailored for expressiveness, and raising an AssertionError is not that explicit.
Much better would be to raise your own exception, or a ValueError.

这篇关于python的`assert`语句可接受的用例是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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