Python 中断言的使用示例?
我已经读过有关何时使用断言与异常的信息,但我仍然没有“明白”。似乎每当我认为我处于应该使用断言的情况时,在后来的开发中我发现我正在“三思而后行”以确保当我调用函数时断言不会失败。由于还有另一个 Python 习惯用法,即更喜欢使用 try- except,因此我通常最终会放弃断言并抛出异常。我还没有找到一个适合使用断言的地方。谁能举出一些好的例子吗?
I've read about when to use assert vs. exceptions, but I'm still not "getting it". It seems like whenever I think I'm in a situation where I should use assert, later on in development I find that I'm "looking before I leap" to make sure the assert doesn't fail when I call the function. Since there's another Python idiom about preferring to use try-except, I generally end up ditching the assert and throwing an exception instead. I have yet to find a place where it seems right to use an assert. Can anyone come up with some good examples?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一个好的指导方针是,当触发意味着代码中存在错误时,使用
assert
。当您的代码假设某些内容并根据该假设执行操作时,建议使用assert
来保护该假设。此assert
失败意味着您的假设不正确,这意味着您的代码不正确。A good guideline is using
assert
when its triggering means a bug in your code. When your code assumes something and acts upon the assumption, it's recommended to protect this assumption with anassert
. Thisassert
failing means your assumption isn't correct, which means your code isn't correct.倾向于使用断言来检查不应该发生的事情。有点像健全性检查。
另一件需要意识到的事情是,断言在优化时会被删除:
tend to use assert to check for things that should never happen. sort of like a sanity check.
Another thing to realize is that asserts are removed when optimized:
一般来说,断言是为了验证您对代码的假设,即在那个时间点,要么断言成功,要么您的实现存在某种错误。例外是实际上期望错误发生并“拥抱”它,即允许您处理它。
Generelly, assert is there to verify an assumption you have about your code, i.e. at that point in time, either the assert succeeds, or your implementation is somehow buggy. An exception is acutally expecting an error to happen and "embracing" it, i.e. allowing you to handle it.
一个很好的例子是检查函数参数的一致性:
A good example is checking the arguments of a function for consistency: